feat(web): full auth screens rework to match design + old-app business rules

Rebuilt tenant/login/register/reset-password to match the design handoff's
01-account screens precisely (previously only loosely approximated), and
ported the old app's real business rules instead of guessing:

- LoginPage: desktop split branding panel (>=900px), terms-agreement
  checkbox gating submit, forgot-password link, password visibility toggle,
  full ctrl-error translation table (lib/tinode/errors.ts, ported from the
  old app's CTRL_ERROR_TEXT_CN/translateCtrlError -- registration/login go
  over native WS, not REST, so client.ts's REASON_MESSAGES never applied).
- RegisterPage: rebuilt as the real unified username-OR-phone form (not
  phone-only) -- username optional unless phone is blank, invite code
  required+validated only on the username-only path, matching the server's
  actual resolveRegistrationAccount rules. connection.ts's
  registerAccountByPhone generalized into registerAccount() supporting both
  paths, including the Tinode.credential(null) crash the old app had to
  work around on the username-only path.
- New ResetPasswordPage wired to /auth/password-reset/* (a different
  endpoint family than registration's /auth/verification-codes/*).
- Shared components: PasswordInput, VerificationCodeButton, Agreement,
  Toast.
- Fixed tinode-sdk.d.ts: the real method is getCurrentUserID(), not the
  invented getAuthenticatedUserID() -- caught live, login crashed past a
  successful auth.
- Fixed a responsive bug present on all four auth pages: fixed w-[380px]
  forms overflowed past the viewport edge below ~430px wide.

Verified end-to-end against the real backend (api.118im.com, tenant
"default"): fresh phone registration, password reset, re-login with the
new password, and the username-only path's invite-code rejection all
round-tripped correctly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Your Name
2026-09-08 01:11:21 +08:00
co-authored by Claude Sonnet 5
parent 63c1b84b41
commit aa1c46ff22
12 changed files with 636 additions and 163 deletions
+153 -84
View File
@@ -1,14 +1,26 @@
import { useRef, useState } from 'react';
import { useState } from 'react';
import { Link, Navigate, useNavigate } from 'react-router-dom';
import { requestVerificationCode, verifyRegisterCode } from '@/lib/api/auth';
import { Agreement } from '@/features/auth/components/Agreement';
import { PasswordInput } from '@/features/auth/components/PasswordInput';
import { VerificationCodeButton } from '@/features/auth/components/VerificationCodeButton';
import { verifyRegisterCode } from '@/lib/api/auth';
import { ImApiError } from '@/lib/api/client';
import { registerAccountByPhone } from '@/lib/tinode/connection';
import { getTinode, registerAccount } from '@/lib/tinode/connection';
import { registerErrorMessage, validateCredentialsMessage } from '@/lib/tinode/errors';
import { useSessionStore } from '@/stores/session';
function toE164(phone: string): string {
return phone.startsWith('+') ? phone : `+86${phone}`;
const USERNAME_RE = /^[a-z0-9]{1,10}$/;
const PHONE_RE = /^\d{11}$/;
const INVITE_RE = /^[A-Za-z]{5}$/;
interface FormErrors {
username?: string;
phone?: string;
code?: string;
password?: string;
invite?: string;
}
export function RegisterPage() {
@@ -16,114 +28,170 @@ export function RegisterPage() {
const tenant = useSessionStore((s) => s.tenant);
const setMyUserId = useSessionStore((s) => s.setMyUserId);
const [username, setUsername] = useState('');
const [phone, setPhone] = useState('');
const [code, setCode] = useState('');
const [password, setPassword] = useState('');
const [invite, setInvite] = useState('');
const [challengeId, setChallengeId] = useState('');
const [resendIn, setResendIn] = useState(0);
const [sendingCode, setSendingCode] = useState(false);
const [agreed, setAgreed] = useState(false);
const [errors, setErrors] = useState<FormErrors>({});
const [formError, setFormError] = useState('');
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState('');
const timerRef = useRef<number | undefined>(undefined);
if (!tenant) return <Navigate to="/tenant" replace />;
const phoneValid = /^1\d{10}$/.test(phone);
const sendCode = async () => {
if (!phoneValid || sendingCode || resendIn > 0) return;
setSendingCode(true);
setError('');
try {
const res = await requestVerificationCode('register', phone);
setChallengeId(res.challenge_id);
setResendIn(res.resend_after_seconds);
window.clearInterval(timerRef.current);
timerRef.current = window.setInterval(() => {
setResendIn((s) => {
if (s <= 1) {
window.clearInterval(timerRef.current);
return 0;
}
return s - 1;
});
}, 1000);
} catch (err) {
setError(err instanceof ImApiError ? err.message : '验证码发送失败,请重试');
} finally {
setSendingCode(false);
}
};
const usingPhone = !!phone;
const submit = async (e: React.FormEvent) => {
e.preventDefault();
if (!phoneValid || !code || password.length < 8 || !challengeId || submitting) return;
const next: FormErrors = {};
if (!username && !phone) next.username = '用户名和手机号至少填写一项';
if (username && !USERNAME_RE.test(username)) next.username = '用户名仅支持 1-10 位小写字母或数字';
if (usingPhone) {
if (!PHONE_RE.test(phone)) next.phone = '请输入 11 位手机号';
if (!challengeId) next.code = '请先获取验证码';
else if (!/^\d{6}$/.test(code)) next.code = '请输入 6 位验证码';
} else if (!INVITE_RE.test(invite)) {
next.invite = '用户名注册需填写 5 位字母邀请码';
}
if (password.length < 8) next.password = '密码至少 8 位';
setErrors(next);
setFormError('');
if (Object.keys(next).length || !agreed || submitting) return;
setSubmitting(true);
setError('');
let verificationToken: string | undefined;
try {
const { verification_token } = await verifyRegisterCode(challengeId, code);
const phoneE164 = toE164(phone);
const ctrl = await registerAccountByPhone({
phoneE164,
if (usingPhone) {
const verified = await verifyRegisterCode(challengeId, code);
verificationToken = verified.verification_token;
}
} catch (err) {
setErrors((e) => ({ ...e, code: err instanceof ImApiError ? err.message : '验证码错误或已过期' }));
setSubmitting(false);
return;
}
try {
const ctrl = await registerAccount({
username,
phone,
password,
verificationToken: verification_token,
challengeId,
inviteCode: invite,
verificationToken,
challengeId: usingPhone ? challengeId : undefined,
});
if (ctrl.code >= 300 && ctrl.text === 'validate credentials') {
setError('账号已创建,但还需要完成验证,此流程正在实现中');
setFormError(validateCredentialsMessage(ctrl.params as { reason?: string; cred?: string[] } | undefined));
return;
}
setMyUserId(ctrl.params?.user as string | null);
const authToken = getTinode().getAuthToken();
sessionStorage.setItem('im-session-token', authToken ? authToken.token : '');
setMyUserId((ctrl.params?.user as string | undefined) ?? null);
navigate('/messages');
} catch (err) {
setError(err instanceof ImApiError ? err.message : (err as Error)?.message || '注册失败,请稍后重试');
setFormError(registerErrorMessage(err));
} finally {
setSubmitting(false);
}
};
return (
<div className="flex h-dvh w-full items-center justify-center bg-surface-page">
<form onSubmit={submit} className="flex w-[380px] flex-col gap-4">
<h1 className="m-0 text-[28px] font-bold text-text-title">创建账号</h1>
{error ? (
<div className="rounded-lg bg-error-strip-bg px-3 py-2.5 text-sm text-error-strip-text">{error}</div>
) : null}
<label className="flex h-[50px] items-center gap-2 rounded-lg bg-surface-input px-3.5">
<span className="text-[15px] text-text-tertiary-2">+86</span>
<input
value={phone}
onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
placeholder="手机号"
className="w-full bg-transparent text-[15px] outline-none"
/>
</label>
<div className="flex gap-2">
<input
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="验证码"
className="h-[50px] flex-1 rounded-lg bg-surface-input px-3.5 text-[15px] outline-none"
/>
<button
type="button"
onClick={sendCode}
disabled={!phoneValid || sendingCode || resendIn > 0}
className="w-32 flex-none rounded-lg bg-accent-soft-bg text-sm text-accent disabled:bg-[#e6e9ee] disabled:text-text-tertiary-3"
>
{resendIn > 0 ? `重新获取 (${resendIn}s)` : '获取验证码'}
</button>
<div className="flex h-dvh w-full items-center justify-center overflow-y-auto bg-surface-page px-6 py-8">
<form onSubmit={submit} className="flex w-full max-w-[380px] flex-col gap-4">
<div className="mb-1 flex flex-col items-center gap-3">
<div className="grid h-[56px] w-[56px] place-items-center rounded-2xl bg-accent text-2xl font-bold text-white">
M
</div>
<strong className="text-xl font-bold text-text-heading">{tenant.name}</strong>
</div>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="密码(至少 8 位)"
className="h-[50px] rounded-lg bg-surface-input px-3.5 text-[15px] outline-none"
/>
<h1 className="m-0 text-[22px] font-bold text-text-title">创建账号</h1>
{formError ? (
<div className="rounded-lg bg-error-strip-bg px-3 py-2.5 text-sm text-error-strip-text">{formError}</div>
) : null}
<div className="flex flex-col gap-1.5">
<input
value={username}
onChange={(e) => setUsername(e.target.value.replace(/[^a-z0-9]/g, '').slice(0, 10))}
placeholder="用户名(1-10位小写字母或数字)"
autoComplete="username"
className={`h-[50px] rounded-lg bg-surface-input px-3.5 text-[15px] outline-none focus:border focus:border-focus-border focus:shadow-focus-ring ${
errors.username ? 'border border-danger-border' : ''
}`}
/>
{errors.username ? <div className="text-xs text-danger-border">{errors.username}</div> : null}
</div>
<div className="flex items-center gap-3 text-xs text-text-tertiary-3">
<div className="h-px flex-1 bg-border-row" />
或
<div className="h-px flex-1 bg-border-row" />
</div>
<div className="flex flex-col gap-1.5">
<label
className={`flex h-[50px] items-center gap-2 rounded-lg bg-surface-input px-3.5 has-focus:border has-focus:shadow-focus-ring ${
errors.phone ? 'border border-danger-border' : 'has-focus:border-focus-border'
}`}
>
<span className="text-[15px] text-text-tertiary-2">+86</span>
<input
value={phone}
onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
placeholder="请输入手机号"
inputMode="numeric"
className="w-full bg-transparent text-[15px] outline-none"
/>
</label>
{errors.phone ? <div className="text-xs text-danger-border">{errors.phone}</div> : null}
</div>
<div className="flex flex-col gap-1.5">
<div className="flex gap-2">
<input
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
placeholder="短信验证码"
inputMode="numeric"
className={`h-[50px] flex-1 rounded-lg bg-surface-input px-3.5 text-[15px] outline-none ${
errors.code ? 'border border-danger-border' : ''
}`}
/>
<VerificationCodeButton
phone={phone}
scene="register"
onChallenge={setChallengeId}
onError={(msg) => setErrors((e) => ({ ...e, code: msg }))}
/>
</div>
{errors.code ? <div className="text-xs text-danger-border">{errors.code}</div> : null}
</div>
<PasswordInput value={password} onChange={setPassword} placeholder="设置密码" autoComplete="new-password" error={errors.password} />
<div className="flex flex-col gap-1.5">
{/* 邀请码大小写敏感(唯一索引按 ascii_bin 排序),不能像其它字段那样统一大小写 */}
<input
value={invite}
onChange={(e) => setInvite(e.target.value.replace(/[^A-Za-z]/g, '').slice(0, 5))}
placeholder="邀请码(5位英文字母,区分大小写)"
autoCapitalize="off"
autoCorrect="off"
className={`h-[50px] rounded-lg bg-surface-input px-3.5 text-[15px] outline-none ${
errors.invite ? 'border border-danger-border' : ''
}`}
/>
{errors.invite ? <div className="text-xs text-danger-border">{errors.invite}</div> : null}
</div>
{!usingPhone ? (
<p className="m-0 text-xs text-text-tertiary-3">未绑定手机号无法自助找回密码,忘记密码后只能联系企业管理员重置</p>
) : null}
<button
type="submit"
disabled={!phoneValid || !code || password.length < 8 || submitting}
disabled={(!username && !phone) || !password || !agreed || submitting}
className="h-[50px] rounded-lg bg-btn text-base font-medium text-white shadow-btn disabled:bg-btn-disabled disabled:shadow-none"
>
{submitting ? '注册中…' : '注册'}
@@ -131,6 +199,7 @@ export function RegisterPage() {
<Link to="/login" className="text-center text-sm text-accent no-underline">
已有账号?返回登录
</Link>
<Agreement checked={agreed} onChange={setAgreed} prefix="注册即认同MeetingIM" />
</form>
</div>
);