103 lines
5.1 KiB
TypeScript
103 lines
5.1 KiB
TypeScript
"use client";
|
|
|
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|
import { useState, type FormEvent } from "react";
|
|
import { toast } from "@/core/ui/feedback";
|
|
|
|
import { Button } from "@/components/ui/button";
|
|
import { Input } from "@/components/ui/input";
|
|
import { getStoredAuth, setStoredAuth } from "@/core/auth";
|
|
import { changeAccountPassword, getAccountPasswordStatus } from "@/core/auth/account-settings-api";
|
|
|
|
import { SettingsSection } from "./settings-section";
|
|
|
|
export function PasswordSettings({ userId }: { userId: string }) {
|
|
const queryClient = useQueryClient();
|
|
const status = useQuery({
|
|
queryKey: ["account-password", userId],
|
|
queryFn: getAccountPasswordStatus,
|
|
});
|
|
const [currentPassword, setCurrentPassword] = useState("");
|
|
const [newPassword, setNewPassword] = useState("");
|
|
const [confirmPassword, setConfirmPassword] = useState("");
|
|
const [pending, setPending] = useState(false);
|
|
const [error, setError] = useState("");
|
|
const hasPassword = status.data?.has_password ?? true;
|
|
const requiresCurrentPassword = status.data?.requires_current_password ?? true;
|
|
|
|
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
|
event.preventDefault();
|
|
if (pending || !status.data) return;
|
|
setError("");
|
|
if (newPassword !== confirmPassword) {
|
|
setError("两次输入的新密码不一致");
|
|
return;
|
|
}
|
|
if (newPassword.length < 8) {
|
|
setError("新密码至少需要 8 位,请避免常见弱密码");
|
|
return;
|
|
}
|
|
const auth = getStoredAuth();
|
|
if (!auth || auth.user_id !== userId) {
|
|
setError("登录账号已变化,请重新打开个人信息");
|
|
return;
|
|
}
|
|
setPending(true);
|
|
try {
|
|
const session = await changeAccountPassword(requiresCurrentPassword ? currentPassword : "", newPassword);
|
|
// Another tab may have changed the active account while the request was pending.
|
|
if (getStoredAuth()?.access_token !== auth.access_token) return;
|
|
if (session.access_token) {
|
|
setStoredAuth({
|
|
...auth,
|
|
access_token: session.access_token,
|
|
token_type: session.token_type ?? auth.token_type,
|
|
expires_in: session.expires_in ?? auth.expires_in,
|
|
needs_setup: false,
|
|
});
|
|
}
|
|
setCurrentPassword("");
|
|
setNewPassword("");
|
|
setConfirmPassword("");
|
|
queryClient.setQueryData(["account-password", userId], { ...status.data, has_password: true, requires_current_password: true, uses_default_password: false });
|
|
void queryClient.invalidateQueries({ queryKey: ["admin", "users"] });
|
|
toast.success("密码与登录口令已同步更新,其他登录会话已失效");
|
|
} catch (cause) {
|
|
setError(cause instanceof Error ? cause.message : "密码修改失败");
|
|
} finally {
|
|
setPending(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<SettingsSection title={hasPassword ? "修改密码" : "设置密码"} description="密码与登录口令共用,修改后原密码和原口令链接失效。">
|
|
{status.isPending ? <p className="text-muted-foreground text-sm">正在读取密码状态…</p> : status.isError ? (
|
|
<div role="alert" className="space-y-3 text-sm">
|
|
<p className="text-destructive">{status.error.message}</p>
|
|
<Button variant="outline" onClick={() => void status.refetch()}>重新加载</Button>
|
|
</div>
|
|
) : (
|
|
<form onSubmit={(event) => void submit(event)} className="space-y-4 rounded-xl border p-5">
|
|
{!hasPassword && <p className="text-muted-foreground text-sm">此账号尚未设置个人密码,当前使用系统口令。请先输入现有口令,再设置个人密码。</p>}
|
|
{requiresCurrentPassword && (
|
|
<div className="space-y-2">
|
|
<label className="text-sm font-medium" htmlFor="account-current-password">当前密码 / 口令</label>
|
|
<Input id="account-current-password" type="password" autoComplete="current-password" required value={currentPassword} onChange={(event) => setCurrentPassword(event.target.value)} disabled={pending} />
|
|
</div>
|
|
)}
|
|
<div className="space-y-2">
|
|
<label className="text-sm font-medium" htmlFor="account-new-password">新密码</label>
|
|
<Input id="account-new-password" type="password" autoComplete="new-password" required minLength={8} maxLength={255} placeholder="至少 8 位,避免常见弱密码" value={newPassword} onChange={(event) => setNewPassword(event.target.value)} disabled={pending} />
|
|
</div>
|
|
<div className="space-y-2">
|
|
<label className="text-sm font-medium" htmlFor="account-confirm-password">确认新密码</label>
|
|
<Input id="account-confirm-password" type="password" autoComplete="new-password" required minLength={8} maxLength={255} value={confirmPassword} onChange={(event) => setConfirmPassword(event.target.value)} disabled={pending} />
|
|
</div>
|
|
{error && <p role="alert" className="text-destructive text-sm">{error}</p>}
|
|
<div className="flex justify-end"><Button type="submit" disabled={pending}>{pending ? "保存中…" : "保存密码"}</Button></div>
|
|
</form>
|
|
)}
|
|
</SettingsSection>
|
|
);
|
|
}
|