Files
NianAIGC/components/account-security-panel.tsx

83 lines
3.3 KiB
TypeScript

"use client";
import { useState } from "react";
import { KeyRound, Loader2 } from "lucide-react";
export function AccountSecurityPanel() {
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [message, setMessage] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
async function submit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
setMessage(null);
setError(null);
if (newPassword.length < 8) {
setError("新密码至少需要 8 位。");
return;
}
if (newPassword !== confirmPassword) {
setError("两次输入的新密码不一致。");
return;
}
setSaving(true);
try {
const response = await fetch("/api/auth/password/change", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ currentPassword, newPassword, confirmPassword })
});
const payload = await response.json().catch(() => ({})) as { error?: string };
if (!response.ok) throw new Error(payload.error || "密码修改失败。");
setCurrentPassword("");
setNewPassword("");
setConfirmPassword("");
setMessage("密码已修改。");
} catch (requestError) {
setError(requestError instanceof Error ? requestError.message : String(requestError));
} finally {
setSaving(false);
}
}
return (
<section className="account-security-card" aria-labelledby="account-security-title">
<header className="account-panel-heading account-security-heading">
<div>
<h2 id="account-security-title"></h2>
</div>
<span className="account-panel-icon" aria-hidden="true"><KeyRound /></span>
</header>
{message ? <div className="account-feedback success" role="status">{message}</div> : null}
{error ? <div className="account-feedback error" role="alert">{error}</div> : null}
<form className="account-security-form" onSubmit={submit}>
<div className="account-security-fields">
<label className="field">
<span></span>
<input type="password" autoComplete="current-password" value={currentPassword} onChange={(event) => setCurrentPassword(event.target.value)} />
</label>
<label className="field">
<span></span>
<input type="password" autoComplete="new-password" value={newPassword} onChange={(event) => setNewPassword(event.target.value)} />
</label>
<label className="field">
<span></span>
<input type="password" autoComplete="new-password" value={confirmPassword} onChange={(event) => setConfirmPassword(event.target.value)} />
</label>
</div>
<footer className="account-form-footer">
<button className="button primary" type="submit" disabled={saving || !currentPassword || !newPassword || !confirmPassword}>
{saving ? <Loader2 className="spin" size={17} /> : <KeyRound size={17} />}
</button>
</footer>
</form>
</section>
);
}