Skip to content

🤯 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.

💄 style(signin): land sign-in UX audit fixes (#16790)

Arvin Xu19c53c4d0a67
diff --git a/locales/en-US/auth.json b/locales/en-US/auth.json
index c303161704b..46094afb987 100644
--- a/locales/en-US/auth.json
+++ b/locales/en-US/auth.json
@@ -83,6 +83,13 @@
"betterAuth.signin.continueWithWechat": "Sign in with WeChat",
"betterAuth.signin.continueWithZitadel": "Sign in with Zitadel",
"betterAuth.signin.emailPlaceholder": "Enter your email or username",
+ "betterAuth.signin.emailSent.changeEmail": "Use a different email",
+ "betterAuth.signin.emailSent.checkSpam": "Didn't get the email? Check your spam folder, or resend it.",
+ "betterAuth.signin.emailSent.magicLinkDescription": "We sent a sign-in link to {{email}}. Open it to finish signing in.",
+ "betterAuth.signin.emailSent.resend": "Resend email",
+ "betterAuth.signin.emailSent.resent": "Email resent — please check your inbox",
+ "betterAuth.signin.emailSent.resetPasswordDescription": "We sent a password reset link to {{email}}. Open it to set a new password.",
+ "betterAuth.signin.emailSent.title": "Check your inbox",
"betterAuth.signin.emailStep.title": "Sign In",
"betterAuth.signin.error": "Sign in failed, please check your email and password",
"betterAuth.signin.forgotPassword": "Forgot password?",
@@ -99,6 +106,7 @@
"betterAuth.signin.orContinueWith": "OR",
"betterAuth.signin.passwordPlaceholder": "Enter your password",
"betterAuth.signin.passwordStep.subtitle": "Enter your password to continue",
+ "betterAuth.signin.passwordStep.title": "Enter your password",
"betterAuth.signin.setPassword": "set a password",
"betterAuth.signin.signupLink": "Sign up now",
"betterAuth.signin.socialError": "Social sign in failed, please try again",
diff --git a/locales/zh-CN/auth.json b/locales/zh-CN/auth.json
index 67b6bc03881..4203f38e5e8 100644
--- a/locales/zh-CN/auth.json
+++ b/locales/zh-CN/auth.json
@@ -83,6 +83,13 @@
"betterAuth.signin.continueWithWechat": "使用微信登录",
"betterAuth.signin.continueWithZitadel": "使用 Zitadel 登录",
"betterAuth.signin.emailPlaceholder": "请输入邮箱或用户名",
+ "betterAuth.signin.emailSent.changeEmail": "换一个邮箱",
+ "betterAuth.signin.emailSent.checkSpam": "没收到邮件?请检查垃圾邮件文件夹,或重新发送。",
+ "betterAuth.signin.emailSent.magicLinkDescription": "已将登录链接发送至 {{email}},点击邮件中的链接即可完成登录。",
+ "betterAuth.signin.emailSent.resend": "重新发送邮件",
+ "betterAuth.signin.emailSent.resent": "邮件已重新发送,请查收",
+ "betterAuth.signin.emailSent.resetPasswordDescription": "已将重置密码链接发送至 {{email}},点击邮件中的链接即可设置新密码。",
+ "betterAuth.signin.emailSent.title": "请查收邮件",
"betterAuth.signin.emailStep.title": "登录",
"betterAuth.signin.error": "登录遇到了问题。请检查账号与密码后重试",
"betterAuth.signin.forgotPassword": "忘记密码?",
@@ -99,6 +106,7 @@
"betterAuth.signin.orContinueWith": "或继续使用",
"betterAuth.signin.passwordPlaceholder": "请输入密码",
"betterAuth.signin.passwordStep.subtitle": "请输入密码以继续",
+ "betterAuth.signin.passwordStep.title": "请输入密码",
"betterAuth.signin.setPassword": "设置密码",
"betterAuth.signin.signupLink": "创建账号",
"betterAuth.signin.socialError": "登录遇到了问题,请重试",
diff --git a/packages/locales/src/default/auth.ts b/packages/locales/src/default/auth.ts
index d27694920a5..00090e1c04b 100644
--- a/packages/locales/src/default/auth.ts
+++ b/packages/locales/src/default/auth.ts
@@ -87,6 +87,16 @@ export default {
'betterAuth.signin.continueWithWechat': 'Sign in with WeChat',
'betterAuth.signin.continueWithZitadel': 'Sign in with Zitadel',
'betterAuth.signin.emailPlaceholder': 'Enter your email or username',
+ 'betterAuth.signin.emailSent.changeEmail': 'Use a different email',
+ 'betterAuth.signin.emailSent.checkSpam':
+ "Didn't get the email? Check your spam folder, or resend it.",
+ 'betterAuth.signin.emailSent.magicLinkDescription':
+ 'We sent a sign-in link to {{email}}. Open it to finish signing in.',
+ 'betterAuth.signin.emailSent.resend': 'Resend email',
+ 'betterAuth.signin.emailSent.resent': 'Email resent — please check your inbox',
+ 'betterAuth.signin.emailSent.resetPasswordDescription':
+ 'We sent a password reset link to {{email}}. Open it to set a new password.',
+ 'betterAuth.signin.emailSent.title': 'Check your inbox',
'betterAuth.signin.emailStep.title': 'Sign In',
'betterAuth.signin.error': 'Sign in failed, please check your email and password',
'betterAuth.signin.forgotPassword': 'Forgot password?',
@@ -104,6 +114,7 @@ export default {
'betterAuth.signin.orContinueWith': 'OR',
'betterAuth.signin.passwordPlaceholder': 'Enter your password',
'betterAuth.signin.passwordStep.subtitle': 'Enter your password to continue',
+ 'betterAuth.signin.passwordStep.title': 'Enter your password',
'betterAuth.signin.setPassword': 'set a password',
'betterAuth.signin.signupLink': 'Sign up now',
'betterAuth.signin.socialError': 'Social sign in failed, please try again',
diff --git a/src/features/Auth/SignIn/SignInEmailSentStep.tsx b/src/features/Auth/SignIn/SignInEmailSentStep.tsx
new file mode 100644
index 00000000000..4aea938594f
--- /dev/null
+++ b/src/features/Auth/SignIn/SignInEmailSentStep.tsx
@@ -0,0 +1,72 @@
+import { Block, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { MailCheck, RefreshCw } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import AuthCard from '@/features/AuthCard';
+
+export type SentEmailType = 'magicLink' | 'resetPassword';
+
+export interface SignInEmailSentStepProps {
+ email: string;
+ onBack: () => void;
+ onResend: () => Promise<void>;
+ sending: boolean;
+ type: SentEmailType;
+}
+
+export const SignInEmailSentStep = ({
+ email,
+ onBack,
+ onResend,
+ sending,
+ type,
+}: SignInEmailSentStepProps) => {
+ const { t } = useTranslation('auth');
+
+ const description =
+ type === 'magicLink'
+ ? t('betterAuth.signin.emailSent.magicLinkDescription', { email })
+ : t('betterAuth.signin.emailSent.resetPasswordDescription', { email });
+
+ return (
+ <AuthCard
+ subtitle={description}
+ title={t('betterAuth.signin.emailSent.title')}
+ footer={
+ <Text align={'center'} fontSize={13} style={{ marginTop: 16 }} type={'secondary'}>
+ <a
+ role="button"
+ style={{ color: 'inherit', cursor: 'pointer', textDecoration: 'underline' }}
+ tabIndex={0}
+ onClick={onBack}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onBack();
+ }
+ }}
+ >
+ {t('betterAuth.signin.emailSent.changeEmail')}
+ </a>
+ </Text>
+ }
+ >
+ <Flexbox gap={16}>
+ <Block horizontal align={'center'} gap={12} padding={16}>
+ <Icon icon={MailCheck} size={20} />
+ <Text type={'secondary'}>{t('betterAuth.signin.emailSent.checkSpam')}</Text>
+ </Block>
+ <Button
+ block
+ icon={<Icon icon={RefreshCw} size={16} />}
+ loading={sending}
+ size="large"
+ onClick={onResend}
+ >
+ {t('betterAuth.signin.emailSent.resend')}
+ </Button>
+ </Flexbox>
+ </AuthCard>
+ );
+};
diff --git a/src/features/Auth/SignIn/SignInEmailStep.tsx b/src/features/Auth/SignIn/SignInEmailStep.tsx
index c0037be8f22..75d7b93fcca 100644
--- a/src/features/Auth/SignIn/SignInEmailStep.tsx
+++ b/src/features/Auth/SignIn/SignInEmailStep.tsx
@@ -1,9 +1,9 @@
import { BRANDING_NAME } from '@lobechat/business-const';
-import { Alert, Button, Flexbox, Icon, Input, Skeleton, Text } from '@lobehub/ui';
+import { Alert, Button, Flexbox, Icon, Input, Text } from '@lobehub/ui';
import { type FormInstance, type InputRef } from 'antd';
import { Badge, Divider, Form } from 'antd';
import { createStaticStyles } from 'antd-style';
-import { ChevronRight, Mail } from 'lucide-react';
+import { Mail } from 'lucide-react';
import { type CSSProperties, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,7 +12,7 @@ import AuthCard from '@/features/AuthCard';
import { AuthAgreement } from '@/features/AuthShell';
const styles = createStaticStyles(({ css, cssVar }) => ({
- setPasswordLink: css`
+ inlineLink: css`
cursor: pointer;
color: ${cssVar.colorPrimary};
text-decoration: underline;
@@ -38,6 +38,8 @@ export interface SignInEmailStepProps {
loading: boolean;
oAuthSSOProviders: string[];
onCheckUser: (values: { email: string }) => Promise<void>;
+ onGoToSignup: () => void;
+ onResetEmail: () => void;
onSetPassword: () => void;
onSocialSignIn: (provider: string) => void;
serverConfigInit: boolean;
@@ -54,6 +56,8 @@ export const SignInEmailStep = ({
serverConfigInit,
socialLoading,
onCheckUser,
+ onGoToSignup,
+ onResetEmail,
onSetPassword,
onSocialSignIn,
}: SignInEmailStepProps) => {
@@ -79,15 +83,12 @@ export const SignInEmailStep = ({
return t(key, { defaultValue: `Continue with ${normalized}` });
};
+ // Config is injected synchronously via window.__SERVER_CONFIG__, so the email
+ // form is the primary path unless the account is social-only.
+ const showEmailForm = !disableEmailPassword && !isSocialOnly;
+
return (
<AuthCard title={t('signin.subtitle', { appName: BRANDING_NAME })}>
- {!serverConfigInit && (
- <Flexbox gap={12}>
- <Skeleton.Button active block size="large" />
- <Skeleton.Button active block size="large" />
- {divider}
- </Flexbox>
- )}
{serverConfigInit && oAuthSSOProviders.length > 0 && (
<Flexbox gap={12}>
{oAuthSSOProviders.map((provider) => {
@@ -121,13 +122,13 @@ export const SignInEmailStep = ({
button
);
})}
- {!disableEmailPassword && divider}
+ {showEmailForm && divider}
</Flexbox>
)}
{serverConfigInit && disableEmailPassword && oAuthSSOProviders.length === 0 && (
<Alert showIcon description={t('betterAuth.signin.ssoOnlyNoProviders')} type="warning" />
)}
- {!disableEmailPassword && (
+ {showEmailForm && (
<Form
form={form}
layout="vertical"
@@ -135,7 +136,6 @@ export const SignInEmailStep = ({
>
<Form.Item
name="email"
- style={{ marginBottom: 0 }}
rules={[
{ message: t('betterAuth.errors.emailRequired'), required: true },
{
@@ -154,30 +154,15 @@ export const SignInEmailStep = ({
autoComplete="username"
inputMode="email"
placeholder={t('betterAuth.signin.emailPlaceholder')}
+ prefix={<Icon icon={Mail} style={{ marginInline: 6 }} />}
ref={emailInputRef}
size="large"
- prefix={
- <Icon
- icon={Mail}
- style={{
- marginInline: 6,
- }}
- />
- }
- style={{
- padding: 6,
- }}
- suffix={
- <Button
- icon={ChevronRight}
- loading={loading}
- title={t('betterAuth.signin.nextStep')}
- variant={'filled'}
- onClick={() => form.submit()}
- />
- }
+ style={{ padding: 6 }}
/>
</Form.Item>
+ <Button block htmlType="submit" loading={loading} size="large" type="primary">
+ {t('betterAuth.signin.nextStep')}
+ </Button>
</Form>
)}
{isSocialOnly && (
@@ -189,7 +174,7 @@ export const SignInEmailStep = ({
<>
{t('betterAuth.signin.socialOnlyHint')}{' '}
<a
- className={styles.setPasswordLink}
+ className={styles.inlineLink}
role="button"
tabIndex={0}
onClick={onSetPassword}
@@ -206,7 +191,44 @@ export const SignInEmailStep = ({
}
/>
)}
+ {isSocialOnly && (
+ <Text align={'center'} fontSize={13} style={{ marginTop: 12 }} type={'secondary'}>
+ <a
+ className={styles.inlineLink}
+ role="button"
+ tabIndex={0}
+ onClick={onResetEmail}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onResetEmail();
+ }
+ }}
+ >
+ {t('betterAuth.signin.emailSent.changeEmail')}
+ </a>
+ </Text>
+ )}
<AuthAgreement />
+ {showEmailForm && (
+ <Text align={'center'} fontSize={13} style={{ marginTop: 16 }} type={'secondary'}>
+ {t('betterAuth.signin.noAccount')}{' '}
+ <a
+ className={styles.inlineLink}
+ role="button"
+ tabIndex={0}
+ onClick={onGoToSignup}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onGoToSignup();
+ }
+ }}
+ >
+ {t('betterAuth.signin.signupLink')}
+ </a>
+ </Text>
+ )}
</AuthCard>
);
};
diff --git a/src/features/Auth/SignIn/SignInPasswordStep.tsx b/src/features/Auth/SignIn/SignInPasswordStep.tsx
index 7e62ffb2808..0eadebd7511 100644
--- a/src/features/Auth/SignIn/SignInPasswordStep.tsx
+++ b/src/features/Auth/SignIn/SignInPasswordStep.tsx
@@ -1,8 +1,7 @@
import { Button, Icon, InputPassword, Text } from '@lobehub/ui';
import { type FormInstance, type InputRef } from 'antd';
import { Form } from 'antd';
-import { cssVar } from 'antd-style';
-import { ChevronLeft, ChevronRight, Lock } from 'lucide-react';
+import { Lock } from 'lucide-react';
import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,6 +9,7 @@ import AuthCard from '@/features/AuthCard';
export interface SignInPasswordStepProps {
email: string;
+ forgotLoading: boolean;
form: FormInstance<{ password: string }>;
loading: boolean;
onBackToEmail: () => void;
@@ -20,6 +20,7 @@ export interface SignInPasswordStepProps {
export const SignInPasswordStep = ({
email,
form,
+ forgotLoading,
loading,
onBackToEmail,
onForgotPassword,
@@ -34,78 +35,72 @@ export const SignInPasswordStep = ({
return (
<AuthCard
- subtitle={t('betterAuth.signin.passwordStep.subtitle')}
- title={'Agent teammates that grow with you'}
+ subtitle={email}
+ title={t('betterAuth.signin.passwordStep.title')}
footer={
- <>
- <Text fontSize={13} type={'secondary'}>
- <a
- role="button"
- style={{ color: 'inherit', cursor: 'pointer', textDecoration: 'underline' }}
- tabIndex={0}
- onClick={onForgotPassword}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- void onForgotPassword();
- }
- }}
- >
- {t('betterAuth.signin.forgotPassword')}
- </a>
- </Text>
- <Button
- icon={ChevronLeft}
- size={'large'}
- style={{ marginTop: 16 }}
+ <Text align={'center'} fontSize={13} style={{ marginTop: 8 }} type={'secondary'}>
+ <a
+ role="button"
+ style={{ color: 'inherit', cursor: 'pointer', textDecoration: 'underline' }}
+ tabIndex={0}
onClick={onBackToEmail}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onBackToEmail();
+ }
+ }}
>
{t('betterAuth.signin.backToEmail')}
- </Button>
- </>
+ </a>
+ </Text>
}
>
- <Text fontSize={20}>{email}</Text>
<Form
form={form}
layout="vertical"
- style={{ marginTop: 12 }}
onFinish={(values) => onSubmit(values as { password: string })}
>
<Form.Item
name="password"
rules={[{ message: t('betterAuth.errors.passwordRequired'), required: true }]}
- style={{ marginBottom: 0 }}
>
<InputPassword
autoComplete="current-password"
placeholder={t('betterAuth.signin.passwordPlaceholder')}
+ prefix={<Icon icon={Lock} style={{ marginInline: 6 }} />}
ref={passwordInputRef}
size="large"
- prefix={
- <Icon
- icon={Lock}
- style={{
- marginInline: 6,
- }}
- />
- }
- style={{
- padding: 6,
- }}
- suffix={
- <Button
- icon={ChevronRight}
- loading={loading}
- style={{ color: cssVar.colorPrimary }}
- title={t('betterAuth.signin.submit')}
- variant={'filled'}
- onClick={() => form.submit()}
- />
- }
+ style={{ padding: 6 }}
/>
</Form.Item>
+ <Button block htmlType="submit" loading={loading} size="large" type="primary">
+ {t('betterAuth.signin.submit')}
+ </Button>
</Form>
+ <Text align={'center'} fontSize={13} style={{ marginTop: 16 }} type={'secondary'}>
+ <a
+ aria-disabled={forgotLoading}
+ role="button"
+ tabIndex={0}
+ style={{
+ color: 'inherit',
+ cursor: forgotLoading ? 'default' : 'pointer',
+ opacity: forgotLoading ? 0.5 : 1,
+ pointerEvents: forgotLoading ? 'none' : undefined,
+ textDecoration: 'underline',
+ }}
+ onClick={onForgotPassword}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ void onForgotPassword();
+ }
+ }}
+ >
+ {t('betterAuth.signin.forgotPassword')}
+ </a>
+ </Text>
</AuthCard>
);
};
diff --git a/src/features/Auth/SignIn/index.tsx b/src/features/Auth/SignIn/index.tsx
index c8e17d37bf9..aeea5302758 100644
--- a/src/features/Auth/SignIn/index.tsx
+++ b/src/features/Auth/SignIn/index.tsx
@@ -1,5 +1,6 @@
'use client';
+import { SignInEmailSentStep } from './SignInEmailSentStep';
import { SignInEmailStep } from './SignInEmailStep';
import { SignInPasswordStep } from './SignInPasswordStep';
import { useSignIn } from './useSignIn';
@@ -9,21 +10,50 @@ const SignIn = () => {
disableEmailPassword,
email,
form,
+ handleBackFromSent,
handleBackToEmail,
handleCheckUser,
handleForgotPassword,
+ handleGoToSignup,
+ handleResendEmail,
handleSignIn,
handleSocialSignIn,
isSocialOnly,
lastAuthProvider,
loading,
oAuthSSOProviders,
+ sending,
+ sentInfo,
serverConfigInit,
socialLoading,
step,
} = useSignIn();
- return step === 'email' ? (
+ if (step === 'emailSent' && sentInfo)
+ return (
+ <SignInEmailSentStep
+ email={sentInfo.email}
+ sending={sending}
+ type={sentInfo.type}
+ onBack={handleBackFromSent}
+ onResend={handleResendEmail}
+ />
+ );
+
+ if (step === 'password')
+ return (
+ <SignInPasswordStep
+ email={email}
+ forgotLoading={sending}
+ form={form as any}
+ loading={loading}
+ onBackToEmail={handleBackToEmail}
+ onForgotPassword={handleForgotPassword}
+ onSubmit={handleSignIn}
+ />
+ );
+
+ return (
<SignInEmailStep
disableEmailPassword={disableEmailPassword}
form={form as any}
@@ -34,18 +64,11 @@ const SignIn = () => {
serverConfigInit={serverConfigInit}
socialLoading={socialLoading}
onCheckUser={handleCheckUser}
+ onGoToSignup={handleGoToSignup}
+ onResetEmail={handleBackToEmail}
onSetPassword={handleForgotPassword}
onSocialSignIn={handleSocialSignIn}
/>
- ) : (
- <SignInPasswordStep
- email={email}
- form={form as any}
- loading={loading}
- onBackToEmail={handleBackToEmail}
- onForgotPassword={handleForgotPassword}
- onSubmit={handleSignIn}
- />
);
};
diff --git a/src/features/Auth/SignIn/useSignIn.test.ts b/src/features/Auth/SignIn/useSignIn.test.ts
index 7ccb76c874c..50ceced5e72 100644
--- a/src/features/Auth/SignIn/useSignIn.test.ts
+++ b/src/features/Auth/SignIn/useSignIn.test.ts
@@ -65,13 +65,14 @@ vi.mock('@/business/client/hooks/useBusinessSignin', () => ({
}));
let mockEnableBusinessFeatures = false;
+let mockEnableMagicLink = false;
vi.mock('@/features/AuthShell', () => ({
useAuthServerConfigStore: (selector: (s: any) => any) =>
selector({
serverConfig: {
disableEmailPassword: false,
enableBusinessFeatures: mockEnableBusinessFeatures,
- enableMagicLink: false,
+ enableMagicLink: mockEnableMagicLink,
oAuthSSOProviders: ['google', 'github'],
},
serverConfigInit: true,
@@ -81,6 +82,8 @@ vi.mock('@/features/AuthShell', () => ({
const mockSetFieldValue = vi.fn();
const mockGetFieldValue = vi.fn();
const mockValidateFields = vi.fn();
+const mockSetFields = vi.fn();
+const mockResetFields = vi.fn();
const mockSubmit = vi.fn();
vi.mock('antd', async () => {
const actual: any = await vi.importActual('antd');
@@ -91,6 +94,8 @@ vi.mock('antd', async () => {
useForm: () => [
{
getFieldValue: mockGetFieldValue,
+ resetFields: mockResetFields,
+ setFields: mockSetFields,
setFieldValue: mockSetFieldValue,
submit: mockSubmit,
validateFields: mockValidateFields,
@@ -112,6 +117,7 @@ describe('useSignIn', () => {
mockLocalStorage.clear();
mockSearchParamsGet.mockReturnValue(null);
mockEnableBusinessFeatures = false;
+ mockEnableMagicLink = false;
mockBusinessSignin.ssoProviders = [];
mockBusinessSignin.getAdditionalData.mockResolvedValue({});
mockBusinessSignin.preSocialSigninCheck.mockResolvedValue(true);
@@ -292,7 +298,7 @@ describe('useSignIn', () => {
},
);
- it('should show error on sign in failure', async () => {
+ it('should surface sign in failure as an inline password error', async () => {
mockSignInEmail.mockResolvedValue({
error: { message: 'Invalid credentials', status: 401 },
});
@@ -312,7 +318,11 @@ describe('useSignIn', () => {
await result.current.handleSignIn({ password: 'wrong' });
});
- expect(mockMessageError).toHaveBeenCalledWith('Invalid credentials');
+ // Error is pinned inline on the password field, not shown as a toast
+ expect(mockSetFields).toHaveBeenCalledWith([
+ { errors: ['Invalid credentials'], name: 'password' },
+ ]);
+ expect(mockMessageError).not.toHaveBeenCalled();
});
it('should redirect to verify-email on 403', async () => {
@@ -467,11 +477,14 @@ describe('useSignIn', () => {
expect(result.current.step).toBe('email');
expect(result.current.email).toBe('');
expect(result.current.isSocialOnly).toBe(false);
+ // The shared form's password (+ any inline error) must be cleared so the
+ // next email doesn't remount pre-filled with the previous account's value.
+ expect(mockResetFields).toHaveBeenCalledWith(['password']);
});
});
describe('handleForgotPassword', () => {
- it('should call requestPasswordReset and show success', async () => {
+ it('should call requestPasswordReset and land on the email-sent state', async () => {
mockRequestPasswordReset.mockResolvedValue(undefined);
mockFetch.mockResolvedValueOnce({
@@ -493,19 +506,128 @@ describe('useSignIn', () => {
expect(mockRequestPasswordReset).toHaveBeenCalledWith(
expect.objectContaining({ email: '[email protected]' }),
);
- expect(mockMessageSuccess).toHaveBeenCalled();
+ // Success is a persistent landing state, not a fleeting toast
+ expect(result.current.step).toBe('emailSent');
+ expect(result.current.sentInfo).toEqual(
+ expect.objectContaining({ email: '[email protected]', type: 'resetPassword' }),
+ );
+ });
+
+ it('should no-op when no email has been resolved yet', async () => {
+ const { result } = renderHook(() => useSignIn());
+
+ await act(async () => {
+ await result.current.handleForgotPassword();
+ });
+
+ expect(mockRequestPasswordReset).not.toHaveBeenCalled();
+ expect(result.current.step).toBe('email');
});
it('should show error on failure', async () => {
mockRequestPasswordReset.mockRejectedValue(new Error('fail'));
+ mockFetch.mockResolvedValueOnce({
+ json: async () => ({ exists: true, hasPassword: true }),
+ ok: true,
+ });
+
const { result } = renderHook(() => useSignIn());
+ await act(async () => {
+ await result.current.handleCheckUser({ email: '[email protected]' });
+ });
+
await act(async () => {
await result.current.handleForgotPassword();
});
expect(mockMessageError).toHaveBeenCalled();
+ expect(result.current.step).toBe('password');
+ });
+ });
+
+ describe('magic link', () => {
+ it('should land on email-sent state when a passwordless user triggers magic link', async () => {
+ mockEnableMagicLink = true;
+ mockSignInMagicLink.mockResolvedValue({ error: null });
+ mockFetch.mockResolvedValueOnce({
+ json: async () => ({ exists: true, hasPassword: false }),
+ ok: true,
+ });
+
+ const { result } = renderHook(() => useSignIn());
+
+ await act(async () => {
+ await result.current.handleCheckUser({ email: '[email protected]' });
+ });
+
+ expect(mockSignInMagicLink).toHaveBeenCalledTimes(1);
+ expect(result.current.step).toBe('emailSent');
+ expect(result.current.sentInfo).toEqual(
+ expect.objectContaining({ email: '[email protected]', type: 'magicLink' }),
+ );
+ });
+ });
+
+ describe('handleResendEmail', () => {
+ it('should resend the password reset email and confirm', async () => {
+ mockRequestPasswordReset.mockResolvedValue(undefined);
+ mockFetch.mockResolvedValueOnce({
+ json: async () => ({ exists: true, hasPassword: true }),
+ ok: true,
+ });
+
+ const { result } = renderHook(() => useSignIn());
+
+ await act(async () => {
+ await result.current.handleCheckUser({ email: '[email protected]' });
+ });
+ await act(async () => {
+ await result.current.handleForgotPassword();
+ });
+
+ mockRequestPasswordReset.mockClear();
+
+ await act(async () => {
+ await result.current.handleResendEmail();
+ });
+
+ expect(mockRequestPasswordReset).toHaveBeenCalledTimes(1);
+ expect(mockMessageSuccess).toHaveBeenCalled();
+ expect(result.current.step).toBe('emailSent');
+ });
+ });
+
+ describe('handleBackFromSent', () => {
+ it('should return to the email entry (not the password step) after a reset email', async () => {
+ mockRequestPasswordReset.mockResolvedValue(undefined);
+ mockFetch.mockResolvedValueOnce({
+ json: async () => ({ exists: true, hasPassword: true }),
+ ok: true,
+ });
+
+ const { result } = renderHook(() => useSignIn());
+
+ await act(async () => {
+ await result.current.handleCheckUser({ email: '[email protected]' });
+ });
+ await act(async () => {
+ await result.current.handleForgotPassword();
+ });
+
+ expect(result.current.step).toBe('emailSent');
+
+ act(() => {
+ result.current.handleBackFromSent();
+ });
+
+ // "Use a different email" must land on the email entry so the label
+ // matches the action, and reset the shared password field.
+ expect(result.current.step).toBe('email');
+ expect(result.current.email).toBe('');
+ expect(result.current.sentInfo).toBeNull();
+ expect(mockResetFields).toHaveBeenCalledWith(['password']);
});
});
diff --git a/src/features/Auth/SignIn/useSignIn.ts b/src/features/Auth/SignIn/useSignIn.ts
index e465baccc4e..305e07f965a 100644
--- a/src/features/Auth/SignIn/useSignIn.ts
+++ b/src/features/Auth/SignIn/useSignIn.ts
@@ -17,7 +17,14 @@ import { EMAIL_REGEX, USERNAME_REGEX } from './SignInEmailStep';
const LAST_AUTH_PROVIDER_KEY = 'lobehub:auth:last-provider:v1';
-type Step = 'email' | 'password';
+type Step = 'email' | 'password' | 'emailSent';
+
+type SentEmailType = 'magicLink' | 'resetPassword';
+
+interface SentEmailInfo {
+ email: string;
+ type: SentEmailType;
+}
interface SignInFormValues {
email: string;
@@ -42,9 +49,13 @@ export const useSignIn = () => {
);
const [form] = Form.useForm<SignInFormValues>();
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);
const [step, setStep] = useState<Step>('email');
const [email, setEmail] = useState('');
+ const [sentInfo, setSentInfo] = useState<SentEmailInfo | null>(null);
const [isSocialOnly, setIsSocialOnly] = useState(false);
const [lastAuthProvider] = useState(() => {
try {
@@ -62,7 +73,8 @@ export const useSignIn = () => {
if (emailParam) form.setFieldValue('email', emailParam);
}, [searchParams, form]);
- const handleSendMagicLink = async (targetEmail?: string) => {
+ const handleSendMagicLink = async (targetEmail?: string): Promise<boolean> => {
+ if (sending) return false;
try {
const emailValue =
targetEmail ||
@@ -70,8 +82,9 @@ export const useSignIn = () => {
.validateFields(['email'])
.then((v) => v.email as string)
.catch(() => null));
- if (!emailValue) return;
+ if (!emailValue) return false;
+ setSending(true);
const callbackUrl = searchParams.get('callbackUrl') || '/';
const { error } = await signIn.magicLink({
callbackURL: callbackUrl,
@@ -81,14 +94,21 @@ export const useSignIn = () => {
});
if (error) {
message.error(error.message || t('betterAuth.signin.magicLinkError'));
- return;
+ return false;
}
- message.success(t('betterAuth.signin.magicLinkSent'));
+ // 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) {
if (!(error as any)?.errorFields) {
console.error('Magic link error:', error);
message.error(t('betterAuth.signin.magicLinkError'));
}
+ return false;
+ } finally {
+ setSending(false);
}
};
@@ -205,7 +225,15 @@ export const useSignIn = () => {
);
if (result.error && result.error.status !== 403) {
- message.error(result.error.message || t('betterAuth.signin.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.setFields([
+ {
+ errors: [result.error.message || t('betterAuth.signin.error')],
+ name: 'password',
+ },
+ ]);
}
} catch (error) {
console.error('Sign in error:', error);
@@ -269,6 +297,10 @@ export const useSignIn = () => {
setStep('email');
setEmail('');
setIsSocialOnly(false);
+ // 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.resetFields(['password']);
};
const handleGoToSignup = () => {
@@ -286,18 +318,49 @@ export const useSignIn = () => {
});
};
- const handleForgotPassword = async () => {
+ // 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);
try {
await requestPasswordReset({
- email,
- redirectTo: `/reset-password?email=${encodeURIComponent(email)}`,
+ email: targetEmail,
+ redirectTo: `/reset-password?email=${encodeURIComponent(targetEmail)}`,
});
- message.success(t('betterAuth.signin.forgotPasswordSent'));
+ return true;
} catch {
message.error(t('betterAuth.signin.forgotPasswordError'));
+ 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) message.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) => {
@@ -311,16 +374,20 @@ export const useSignIn = () => {
disableEmailPassword,
email,
form,
+ handleBackFromSent,
handleBackToEmail,
handleCheckUser,
handleForgotPassword,
handleGoToSignup,
+ handleResendEmail,
handleSignIn,
handleSocialSignIn,
isSocialOnly,
lastAuthProvider,
loading,
oAuthSSOProviders: sortedProviders,
+ sending,
+ sentInfo,
serverConfigInit: enableBusinessFeatures ? true : serverConfigInit,
socialLoading,
step,