Files
UHD_Media_Tool/apps/web/app/components/console/account-menu.tsx
T
2026-09-28 02:09:39 +08:00

336 lines
13 KiB
TypeScript

import { PasswordChangeRequest, type SessionInfo, TotpCode } from "@umt/contracts";
import { KeyRound, LoaderCircle, LogOut, ShieldCheck, UserRound } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { z } from "zod";
import { useChangePassword, useLogout, useTotpAction, useTotpStatus } from "~/api/auth.ts";
import { Button } from "~/components/ui/button.tsx";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "~/components/ui/dialog.tsx";
import { Input } from "~/components/ui/input.tsx";
import { Popover, PopoverContent, PopoverTrigger } from "~/components/ui/popover.tsx";
import { errorMessage, LOGIN_PATH } from "~/lib/api.ts";
import { formatDateTime } from "~/lib/utils.ts";
import { FormField, zodFieldErrors } from "./form-field.tsx";
const PasswordForm = PasswordChangeRequest.extend({ confirm: z.string() }).refine((v) => v.newPassword === v.confirm, {
message: "两次输入的新密码不一致",
path: ["confirm"],
});
function ChangePasswordDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (o: boolean) => void }) {
const change = useChangePassword();
const [form, setForm] = useState({ currentPassword: "", newPassword: "", confirm: "" });
const [errors, setErrors] = useState<Record<string, string>>({});
const submit = async (e: React.FormEvent) => {
e.preventDefault();
const parsed = PasswordForm.safeParse(form);
if (!parsed.success) {
setErrors(zodFieldErrors(parsed.error.issues));
return;
}
setErrors({});
try {
const r = await change.mutateAsync({ currentPassword: form.currentPassword, newPassword: form.newPassword });
toast.success(r.revokedSessions ? `密码已修改,已注销其它 ${r.revokedSessions} 个会话` : "密码已修改");
setForm({ currentPassword: "", newPassword: "", confirm: "" });
onOpenChange(false);
} catch (err) {
const msg = errorMessage(err);
if (/旧密码|当前密码|password/i.test(msg)) setErrors({ currentPassword: "当前密码不正确" });
else toast.error(msg);
}
};
const set = (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) =>
setForm((f) => ({ ...f, [k]: e.target.value }));
return (
<Dialog open={open} onOpenChange={(o) => !change.isPending && onOpenChange(o)}>
<DialogContent>
<DialogHeader>
<DialogTitle>修改密码</DialogTitle>
<DialogDescription>修改后其它设备上的会话会被注销,当前会话保留。</DialogDescription>
</DialogHeader>
<form id="pwd-form" onSubmit={submit} className="grid gap-1" noValidate>
<FormField label="当前密码" htmlFor="pwd-cur" error={errors.currentPassword}>
<Input
id="pwd-cur"
type="password"
autoComplete="current-password"
value={form.currentPassword}
onChange={set("currentPassword")}
aria-invalid={!!errors.currentPassword}
/>
</FormField>
<FormField label="新密码" htmlFor="pwd-new" error={errors.newPassword} hint="至少 10 个字符">
<Input
id="pwd-new"
type="password"
autoComplete="new-password"
value={form.newPassword}
onChange={set("newPassword")}
aria-invalid={!!errors.newPassword}
/>
</FormField>
<FormField label="确认新密码" htmlFor="pwd-confirm" error={errors.confirm}>
<Input
id="pwd-confirm"
type="password"
autoComplete="new-password"
value={form.confirm}
onChange={set("confirm")}
aria-invalid={!!errors.confirm}
/>
</FormField>
</form>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={change.isPending}>
取消
</Button>
<Button type="submit" form="pwd-form" disabled={change.isPending}>
{change.isPending ? <LoaderCircle className="animate-spin" /> : null}
保存
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
/** 二次验证(TOTP):未开启 → 生成密钥 → 在验证器里添加 → 输入 6 位码确认;已开启 → 当前密码 + 验证码关闭 */
function TotpDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (o: boolean) => void }) {
const status = useTotpStatus(open);
const action = useTotpAction();
const [setup, setSetup] = useState<{ secret: string; uri: string } | null>(null);
const [code, setCode] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const enabled = status.data?.enabled === true;
const reset = () => {
setSetup(null);
setCode("");
setPassword("");
setError(null);
};
const close = (o: boolean) => {
if (action.isPending) return;
if (!o) reset();
onOpenChange(o);
};
const begin = async () => {
setError(null);
try {
const r = await action.mutateAsync({ action: "begin" });
if (r.secret && r.otpauthUri) setSetup({ secret: r.secret, uri: r.otpauthUri });
} catch (err) {
setError(errorMessage(err));
}
};
const submit = async (e: React.FormEvent) => {
e.preventDefault();
if (!TotpCode.safeParse(code).success) {
setError("验证码为 6 位数字");
return;
}
setError(null);
try {
if (enabled) {
if (!password) {
setError("输入当前密码");
return;
}
await action.mutateAsync({ action: "disable", password, code });
toast.success("已关闭二次验证");
} else {
await action.mutateAsync({ action: "enable", code });
toast.success("已开启二次验证");
}
reset();
onOpenChange(false);
} catch (err) {
setError(errorMessage(err));
}
};
const grouped = setup?.secret.replace(/(.{4})/g, "$1 ").trim();
return (
<Dialog open={open} onOpenChange={close}>
<DialogContent>
<DialogHeader>
<DialogTitle>二次验证(TOTP)</DialogTitle>
<DialogDescription>
{status.isLoading
? "读取状态…"
: enabled
? "已开启。关闭需要当前密码和验证码。"
: "未开启。开启后登录还要输入验证器里的 6 位验证码。"}
</DialogDescription>
</DialogHeader>
{!enabled && !setup ? (
<div className="grid gap-2">
{status.data?.pending ? (
<p className="text-meta text-muted-foreground">有一个未确认的密钥;重新生成会作废它。</p>
) : null}
{error ? <p className="text-meta text-destructive">{error}</p> : null}
</div>
) : (
<form id="totp-form" onSubmit={submit} className="grid gap-1" noValidate>
{setup ? (
<div className="mb-2 grid gap-1.5">
<p className="text-meta text-muted-foreground">
在验证器里手动输入下面的密钥,或粘贴 otpauth 链接。密钥只显示这一次。
</p>
<code className="rounded-md bg-muted px-2 py-1.5 font-mono text-sm break-all select-all">
{grouped}
</code>
<code className="rounded-md bg-muted px-2 py-1.5 font-mono text-meta break-all text-muted-foreground select-all">
{setup.uri}
</code>
</div>
) : null}
{enabled ? (
<FormField label="当前密码" htmlFor="totp-pwd">
<Input
id="totp-pwd"
type="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</FormField>
) : null}
<FormField label="验证码" htmlFor="totp-code" error={error ?? undefined}>
<Input
id="totp-code"
inputMode="numeric"
autoComplete="one-time-code"
maxLength={6}
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))}
aria-invalid={!!error}
/>
</FormField>
</form>
)}
<DialogFooter>
<Button variant="outline" onClick={() => close(false)} disabled={action.isPending}>
取消
</Button>
{!enabled && !setup ? (
<Button onClick={begin} disabled={action.isPending || status.isLoading}>
{action.isPending ? <LoaderCircle className="animate-spin" /> : null}
生成密钥
</Button>
) : (
<Button
type="submit"
form="totp-form"
variant={enabled ? "destructive" : "default"}
disabled={action.isPending}
>
{action.isPending ? <LoaderCircle className="animate-spin" /> : null}
{enabled ? "关闭二次验证" : "确认开启"}
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
}
/** 右上角账户弹层:当前身份、会话到期、改密、二次验证、登出 */
export function AccountMenu({ session }: { session: SessionInfo }) {
const [open, setOpen] = useState(false);
const [pwdOpen, setPwdOpen] = useState(false);
const [totpOpen, setTotpOpen] = useState(false);
const logout = useLogout();
const actor = session.actor;
const isCookie = !!session.expiresAt;
const doLogout = async () => {
try {
await logout.mutateAsync();
} catch {
// 会话已失效也照样回登录页
}
window.location.assign(LOGIN_PATH);
};
return (
<>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button variant="outline" size="sm" className="max-w-40" aria-label="账户">
<UserRound />
<span className="hidden truncate sm:inline">{actor?.name ?? "账户"}</span>
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-64 p-2">
<div className="px-2 pt-1 pb-2">
<p className="text-label font-semibold tracking-[0.18em] text-muted-foreground uppercase">当前账户</p>
<p className="mt-1 truncate text-sm font-medium text-foreground">{actor?.name ?? "—"}</p>
<p className="text-meta text-muted-foreground">
{actor?.type === "api_key" ? "API Key 调用" : "管理员"}
{isCookie ? ` · 会话到 ${formatDateTime(session.expiresAt)}` : ""}
</p>
</div>
<div className="border-t border-border pt-1">
{isCookie ? (
<button
type="button"
onClick={() => {
setOpen(false);
setPwdOpen(true);
}}
className="flex w-full cursor-pointer items-center gap-2.5 rounded-lg px-2 py-2 text-left text-body text-foreground hover:bg-foreground/[0.06]"
>
<KeyRound className="h-4 w-4 text-muted-foreground" />
修改密码
</button>
) : null}
{isCookie ? (
<button
type="button"
onClick={() => {
setOpen(false);
setTotpOpen(true);
}}
className="flex w-full cursor-pointer items-center gap-2.5 rounded-lg px-2 py-2 text-left text-body text-foreground hover:bg-foreground/[0.06]"
>
<ShieldCheck className="h-4 w-4 text-muted-foreground" />
二次验证
<span className="ml-auto text-meta text-muted-foreground">
{session.totpEnabled ? "已开启" : "未开启"}
</span>
</button>
) : null}
<button
type="button"
onClick={doLogout}
disabled={logout.isPending}
className="flex w-full cursor-pointer items-center gap-2.5 rounded-lg px-2 py-2 text-left text-body text-foreground hover:bg-foreground/[0.06] disabled:opacity-50"
>
<LogOut className="h-4 w-4 text-muted-foreground" />
退出登录
</button>
</div>
</PopoverContent>
</Popover>
<ChangePasswordDialog open={pwdOpen} onOpenChange={setPwdOpen} />
<TotpDialog open={totpOpen} onOpenChange={setTotpOpen} />
</>
);
}