Files

82 lines
4.7 KiB
TypeScript
Raw Permalink Normal View History

'use client';
import { appPath } from '@/lib/base-path';
import { useState, type FormEvent } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ArrowLeft, CircleAlert, Eye, EyeOff, Info, LoaderCircle, LogOut } from 'lucide-react';
export function PasswordForm({ username, mustChangePassword, passwordSet = true }: { username: string; mustChangePassword: boolean; passwordSet?: boolean }) {
const router = useRouter();
const [visible, setVisible] = useState(false);
const [busy, setBusy] = useState(false);
const [leaving, setLeaving] = useState(false);
const [error, setError] = useState('');
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const fields = new FormData(event.currentTarget);
setError('');
if (fields.get('newPassword') !== fields.get('confirmation')) {
setError('两次输入的新密码不一致,请重新确认。');
event.currentTarget.querySelector<HTMLInputElement>('#confirmation')?.focus();
return;
}
setBusy(true);
try {
const response = await fetch(appPath('/api/auth/password'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...(passwordSet ? { currentPassword: fields.get('currentPassword') } : {}), newPassword: fields.get('newPassword') }),
});
const data = await response.json() as { error?: string };
if (!response.ok) throw new Error(data.error || '修改失败,请稍后重试。');
router.replace('/');
router.refresh();
} catch (cause) {
setError(cause instanceof Error ? cause.message : '无法连接服务,请检查网络后重试。');
setBusy(false);
}
}
async function logout() {
setLeaving(true);
setError('');
try {
const response = await fetch(appPath('/api/auth/logout'), { method: 'POST' });
if (!response.ok) throw new Error('退出登录失败,请重试。');
router.replace('/login');
router.refresh();
} catch (cause) {
setError(cause instanceof Error ? cause.message : '退出登录失败,请重试。');
setLeaving(false);
}
}
return <>
{!passwordSet && <div className="info-banner account-password-notice"><Info size={18} /><span>你当前通过飞书登录。设置系统密码后,也可使用上方账号和密码登录。</span></div>}
{mustChangePassword && <div className="info-banner account-password-notice"><Info size={18} /><span>请将管理员分配的临时密码改为自己的密码,完成后即可进入工作台。</span></div>}
<form className="account-form" onSubmit={submit} aria-busy={busy}>
<input type="text" name="username" value={username} autoComplete="username" readOnly hidden />
{error && <div className="error-banner" role="alert"><CircleAlert size={18} /><span>{error}</span></div>}
<fieldset disabled={busy || leaving}>
{passwordSet && <label className="account-field" htmlFor="currentPassword">{mustChangePassword ? '临时密码' : '当前密码'}
<input id="currentPassword" name="currentPassword" type={visible ? 'text' : 'password'} autoComplete="current-password" required maxLength={128} autoFocus />
</label>}
<div className="account-field"><label htmlFor="newPassword">新密码</label>
<input id="newPassword" name="newPassword" type={visible ? 'text' : 'password'} autoComplete="new-password" required minLength={12} maxLength={128} aria-describedby="password-guidance" autoFocus={!passwordSet} />
<small id="password-guidance">12–128 个字符,可使用方便记忆的长密码。</small>
</div>
<label className="account-field" htmlFor="confirmation">确认新密码
<input id="confirmation" name="confirmation" type={visible ? 'text' : 'password'} autoComplete="new-password" required minLength={12} maxLength={128} />
</label>
<button className="text-button account-show-password" type="button" onClick={() => setVisible(!visible)} aria-pressed={visible}>{visible ? <EyeOff size={17} /> : <Eye size={17} />}{visible ? '隐藏密码' : '显示密码'}</button>
<button className="btn primary account-submit" type="submit">{busy ? <><LoaderCircle className="account-spinner" size={18} />正在保存…</> : '保存密码并进入工作台'}</button>
</fieldset>
</form>
<div className="account-form-footer">
{!mustChangePassword && <Link href="/" className="text-button"><ArrowLeft size={16} />返回工作台</Link>}
<button className="text-button" onClick={logout} disabled={busy || leaving}><LogOut size={16} />{leaving ? '正在退出…' : '退出登录'}</button>
</div>
</>;
}