Files
tap/components/account/login-form.tsx
T

50 lines
2.7 KiB
TypeScript
Raw Normal View History

'use client';
import { appPath } from '@/lib/base-path';
import { useState, type FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowRight, CircleAlert, Eye, EyeOff, LoaderCircle } from 'lucide-react';
export function LoginForm({ returnTo = '/' }: { returnTo?: string }) {
const router = useRouter();
const [visible, setVisible] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const fields = new FormData(event.currentTarget);
setBusy(true);
setError('');
try {
const response = await fetch(appPath('/api/auth/login'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: String(fields.get('username')).trim(), password: fields.get('password') }),
});
const data = await response.json() as { error?: string; user?: { mustChangePassword: boolean } };
if (!response.ok || !data.user) throw new Error(data.error || '暂时无法登录,请稍后重试。');
router.replace(data.user.mustChangePassword ? '/account/password' : returnTo);
router.refresh();
} catch (cause) {
setError(cause instanceof Error ? cause.message : '无法连接服务,请检查网络后重试。');
setBusy(false);
}
}
return <form className="account-form" onSubmit={submit} aria-busy={busy}>
{error && <div className="error-banner" role="alert"><CircleAlert size={18} /><span>{error}</span></div>}
<fieldset disabled={busy}>
<label className="account-field" htmlFor="username">账号
<input id="username" name="username" autoComplete="username" autoCapitalize="none" spellCheck={false} required maxLength={64} placeholder="请输入管理员分配的账号" autoFocus />
</label>
<label className="account-field" htmlFor="password">密码</label>
<div className="account-password-input">
<input id="password" name="password" type={visible ? 'text' : 'password'} autoComplete="current-password" required maxLength={128} placeholder="请输入密码" />
<button type="button" onClick={() => setVisible(!visible)} aria-label={visible ? '隐藏密码' : '显示密码'} aria-pressed={visible}>{visible ? <EyeOff size={19} /> : <Eye size={19} />}</button>
</div>
<button className="btn primary account-submit" type="submit">{busy ? <><LoaderCircle className="account-spinner" size={18} />正在登录…</> : <>登录工作台<ArrowRight size={18} /></>}</button>
</fieldset>
<p className="account-help">需要开通账号或忘记密码,请联系系统管理员。</p>
</form>;
}