Files
deerflow-code/frontend-web/src/pages/LoginWhitelistPage.tsx
T
吉鑫升andClaude Opus 4.8 9572b66ecb feat(白名单): 账号级登录口令——管理员设明文口令,用户凭 /login/<用户名>?password= 直登
白名单管理页可给单个账号设明文登录口令(users.login_password,可空):
设置后该账号用户名直登(/login/username)须带匹配 ?password=,且优先于全局共享口令门;
未设口令的账号行为不变。前端登录 URL 已支持透传 ?password=,无需改登录页。

- 后端:UserRow/User 新增 login_password + 仓储映射;/login/username 账号级口令闸门
  (_lookup_user_by_username 仅查不建);新管理员接口 PUT /users/{id}/login-password;
  UserListItem 暴露明文(仅 admin 列表);migration 20260625_04 + 幂等补列 SQL。
- 前端:白名单页新增「登录口令」列(设置/修改/清除 + 复制登录链接);
  core/auth api+hooks 增 setUserLoginPassword/useSetUserLoginPassword(含 Y-Log)。
- 文档:根 + 后端 CLAUDE.md 同步。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 11:03:39 +08:00

342 lines
18 KiB
TypeScript

"use client";
import { Fragment, useMemo, useState } from "react";
import { Navigate } from "react-router-dom";
import { Copy, Info, KeyRound, Link2, Search, ShieldCheck, UserCheck, X } from "lucide-react";
import { toast } from "sonner";
import { Switch } from "@/components/ui/switch";
import type { UserListItem } from "@/core/auth/api";
import { getStoredAuth } from "@/core/auth";
import { useAllUsers, useSetUserApproval, useSetUserLoginPassword } from "@/core/auth/hooks";
import {
useLoginWhitelistEnabled,
useSetLoginWhitelistEnabled,
} from "@/strategy-components/api/login-whitelist";
/**
* 登录白名单管理(管理员)—— 黑名单模式。
*
* 顶部一个「总开关」:关 = 所有人可登录;开 = 仅被管理员「取消放行」的用户被拦。
* 新账号(含从未登录过的用户)默认即已放行,管理员在下方对个别用户「取消放行」
* 来封禁;admin 始终可登录,不受开关与放行状态影响。
*/
export default function LoginWhitelistPage() {
const isAdmin = getStoredAuth()?.system_role === "admin";
const { data: enabled, isLoading: loadingSwitch } = useLoginWhitelistEnabled();
const setEnabled = useSetLoginWhitelistEnabled();
const { data: users = [], isLoading: loadingUsers } = useAllUsers(isAdmin);
const setApproval = useSetUserApproval();
const setLoginPassword = useSetUserLoginPassword();
const [query, setQuery] = useState("");
const [pendingId, setPendingId] = useState<string | null>(null);
// 口令编辑:当前展开编辑的用户 id + 输入草稿(明文,便于管理员直接查看/复制)。
const [editingId, setEditingId] = useState<string | null>(null);
const [pwdDraft, setPwdDraft] = useState("");
const q = query.trim().toLowerCase();
const visibleUsers = useMemo(
() => (!q ? users : users.filter((u) => u.email.toLowerCase().includes(q) || u.id.toLowerCase().includes(q))),
[users, q],
);
const approvedCount = users.filter((u) => u.approved || u.system_role === "admin").length;
const handleToggleSwitch = async (next: boolean) => {
try {
await setEnabled.mutateAsync(next);
toast.success(next ? "已启用登录白名单" : "已停用登录白名单(所有人可登录)");
} catch (err) {
toast.error(err instanceof Error ? err.message : "保存失败");
}
};
const handleToggleApproval = async (userId: string, next: boolean) => {
setPendingId(userId);
try {
await setApproval.mutateAsync({ userId, approved: next });
toast.success(next ? "已放行该用户" : "已取消放行(下次登录被拦)");
} catch (err) {
toast.error(err instanceof Error ? err.message : "保存失败");
} finally {
setPendingId(null);
}
};
// 用户名直登链接:`<当前源>/#/login/<邮箱本地部分>?password=<口令>`。用户名取邮箱
// `@` 前缀(用户名直登据此解析回同一账号);base 取去掉 hash 的当前地址,保留可能的
// 部署子路径。
const buildLoginLink = (user: UserListItem, password: string) => {
const localPart = (user.email.split("@")[0] || "").trim();
const base = window.location.href.split("#")[0];
return `${base}#/login/${encodeURIComponent(localPart)}?password=${encodeURIComponent(password)}`;
};
const copyText = async (text: string, okMsg: string) => {
try {
await navigator.clipboard.writeText(text);
toast.success(okMsg);
} catch {
toast.error("复制失败,请手动复制");
}
};
const openEditor = (user: UserListItem) => {
setEditingId(user.id);
setPwdDraft(user.login_password ?? "");
};
const closeEditor = () => {
setEditingId(null);
setPwdDraft("");
};
const handleSavePassword = async (user: UserListItem) => {
const pwd = pwdDraft.trim();
if (!pwd) return;
try {
await setLoginPassword.mutateAsync({ userId: user.id, password: pwd });
toast.success("已设置登录口令");
closeEditor();
} catch (err) {
toast.error(err instanceof Error ? err.message : "保存失败");
}
};
const handleClearPassword = async (user: UserListItem) => {
try {
await setLoginPassword.mutateAsync({ userId: user.id, password: null });
toast.success("已清除登录口令");
closeEditor();
} catch (err) {
toast.error(err instanceof Error ? err.message : "清除失败");
}
};
if (!isAdmin) return <Navigate to="/page/workspace/chats/new" replace />;
return (
<div className="h-full overflow-auto bg-slate-50/60 px-4 py-6 sm:px-6 lg:px-8">
<div className="mx-auto max-w-4xl">
{/* 顶部信息卡 + 总开关 */}
<div className="relative mb-6 overflow-hidden rounded-3xl border border-slate-200/60 bg-white p-6 shadow-sm md:p-8">
<div className="pointer-events-none absolute right-0 top-0 select-none p-8 opacity-[0.03]">
<ShieldCheck className="size-44 text-slate-900" />
</div>
<div className="relative">
<div className="mb-4 flex flex-col justify-between gap-4 md:flex-row md:items-center">
<div>
<span className="mb-3 inline-flex select-none items-center gap-1.5 rounded-full border border-red-100 bg-red-50 px-3 py-1 text-xs font-semibold text-red-600">
<ShieldCheck className="size-3" />
登录访问控制
</span>
<h1 className="flex items-center gap-3 text-2xl font-bold tracking-tight text-slate-800 md:text-3xl">
白名单管理
<span className="rounded-lg border border-slate-200/60 bg-slate-100 px-2.5 py-0.5 font-mono text-xs font-medium text-slate-500">
{users.length} 用户 / {approvedCount} 可登录
</span>
</h1>
</div>
<div className="flex items-center gap-3 rounded-2xl border border-slate-200/60 bg-slate-50/70 px-4 py-3">
<div className="text-right">
<div className="text-sm font-semibold text-slate-700">登录白名单</div>
<div className="text-xs text-slate-500">{enabled ? "已启用:仅被取消放行的用户被拦" : "已停用:所有人可登录"}</div>
</div>
<Switch
checked={Boolean(enabled)}
disabled={loadingSwitch || setEnabled.isPending}
onCheckedChange={handleToggleSwitch}
/>
</div>
</div>
<p className="flex max-w-2xl items-start gap-2.5 rounded-2xl border border-slate-200/50 bg-slate-50/70 p-3.5 text-sm leading-relaxed text-slate-600">
<Info className="mt-0.5 size-4 shrink-0 text-slate-400" />
<span>
<strong>黑名单模式</strong>:新账号(含从未登录过的用户)<strong>默认已放行</strong>,可直接登录使用。开关<strong>关闭</strong>时所有人可正常登录;
<strong> 开启</strong>后仅被管理员<strong>取消放行</strong>的用户被拦在登录外,请在下方对要封禁的用户取消放行。
<strong> 管理员(admin)始终可登录</strong>,不受开关与放行状态影响。
</span>
</p>
</div>
</div>
{/* 搜索栏 */}
<div className="mb-6 rounded-2xl border border-slate-200/60 bg-white p-4 shadow-sm md:p-5">
<div className="relative w-full md:w-80">
<Search className="absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-slate-400" />
<input
type="text"
placeholder="搜索邮箱 / 用户ID…"
value={query}
onChange={(e) => setQuery(e.target.value)}
className="w-full rounded-xl border border-slate-200 bg-slate-50/50 py-2 pl-10 pr-4 text-sm transition-all hover:border-slate-300 focus:border-red-500 focus:outline-none focus:ring-4 focus:ring-red-500/5"
/>
</div>
</div>
{/* 用户列表 */}
<div className="overflow-hidden rounded-2xl border border-slate-200/60 bg-white shadow-sm">
<div className="grid grid-cols-[1fr_auto_auto_auto] items-center gap-3 border-b border-slate-200/60 bg-slate-50/70 px-4 py-2.5 text-xs font-semibold text-slate-500">
<span>用户</span>
<span className="px-1 text-center">问答</span>
<span className="px-1 text-center">登录口令</span>
<span className="px-1 text-center">放行</span>
</div>
{loadingUsers ? (
<div className="px-4 py-12 text-center text-sm text-slate-400">加载中…</div>
) : visibleUsers.length === 0 ? (
<div className="px-4 py-12 text-center text-sm text-slate-400">
{users.length === 0 ? "暂无注册用户" : "没有匹配的用户"}
</div>
) : (
<ul className="divide-y divide-slate-100">
{visibleUsers.map((user) => {
const isUserAdmin = user.system_role === "admin";
const allowed = user.approved || isUserAdmin;
const hasPwd = Boolean(user.login_password);
const isEditing = editingId === user.id;
return (
<Fragment key={user.id}>
<li className="grid grid-cols-[1fr_auto_auto_auto] items-center gap-3 px-4 py-3 transition-colors hover:bg-slate-50/60">
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-medium text-slate-800">{user.email}</span>
{isUserAdmin ? (
<span className="inline-flex items-center gap-1 rounded-md border border-amber-200 bg-amber-50 px-1.5 py-0.5 text-[11px] font-semibold text-amber-600">
<UserCheck className="size-3" />
管理员
</span>
) : allowed ? (
<span className="rounded-md border border-emerald-200 bg-emerald-50 px-1.5 py-0.5 text-[11px] font-semibold text-emerald-600">
已放行
</span>
) : (
<span className="rounded-md border border-rose-200 bg-rose-50 px-1.5 py-0.5 text-[11px] font-semibold text-rose-600">
已拦截
</span>
)}
</div>
<div className="truncate font-mono text-xs text-slate-400">{user.id}</div>
</div>
<div className="px-1 text-center text-sm tabular-nums text-slate-500">{user.qa_count}</div>
{/* 登录口令:设置 / 修改 + 复制登录链接 */}
<div className="px-1">
<div className="flex items-center justify-center gap-1.5">
<button
type="button"
onClick={() => (isEditing ? closeEditor() : openEditor(user))}
title={hasPwd ? "已设登录口令,点击修改" : "设置登录口令"}
className={`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-[11px] font-semibold transition-colors ${
hasPwd
? "border-emerald-200 bg-emerald-50 text-emerald-600 hover:bg-emerald-100"
: "border-slate-200 bg-slate-50 text-slate-500 hover:bg-slate-100"
}`}
>
<KeyRound className="size-3" />
{hasPwd ? "已设" : "设置"}
</button>
{hasPwd && (
<button
type="button"
onClick={() => copyText(buildLoginLink(user, user.login_password ?? ""), "已复制登录链接")}
title="复制登录链接"
className="inline-flex items-center rounded-md border border-slate-200 bg-white px-1.5 py-1 text-slate-500 transition-colors hover:bg-slate-50 hover:text-slate-700"
>
<Link2 className="size-3" />
</button>
)}
</div>
</div>
<div className="px-1">
<Switch
checked={allowed}
disabled={isUserAdmin || (setApproval.isPending && pendingId === user.id)}
onCheckedChange={(v) => handleToggleApproval(user.id, v)}
/>
</div>
</li>
{isEditing && (
<li className="bg-slate-50/70 px-4 py-4">
<div className="rounded-xl border border-slate-200/70 bg-white p-4 shadow-sm">
<div className="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-600">
<KeyRound className="size-3.5 text-slate-400" />
为 <span className="font-mono text-slate-800">{user.email}</span> 设置登录口令
</div>
<p className="mb-3 text-[11px] leading-relaxed text-slate-400">
设置后该账号需用此口令登录:
<code className="rounded bg-slate-100 px-1 text-slate-500">/login/用户名?password=口令</code>
。口令以明文随链接传输,仅用于临时开通,请妥善保管。
</p>
<div className="flex flex-wrap items-center gap-2">
<input
type="text"
value={pwdDraft}
onChange={(e) => setPwdDraft(e.target.value)}
placeholder="输入登录口令"
onKeyDown={(e) => {
if (e.key === "Enter") void handleSavePassword(user);
}}
className="w-56 rounded-lg border border-slate-200 bg-slate-50/50 px-3 py-1.5 text-sm transition-all hover:border-slate-300 focus:border-red-500 focus:outline-none focus:ring-4 focus:ring-red-500/5"
/>
<button
type="button"
disabled={!pwdDraft.trim() || setLoginPassword.isPending}
onClick={() => void handleSavePassword(user)}
className="inline-flex items-center gap-1 rounded-lg bg-red-600 px-3 py-1.5 text-sm font-semibold text-white transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:opacity-50"
>
保存
</button>
{hasPwd && (
<button
type="button"
disabled={setLoginPassword.isPending}
onClick={() => void handleClearPassword(user)}
className="inline-flex items-center gap-1 rounded-lg border border-rose-200 bg-rose-50 px-3 py-1.5 text-sm font-semibold text-rose-600 transition-colors hover:bg-rose-100 disabled:opacity-50"
>
清除
</button>
)}
<button
type="button"
onClick={closeEditor}
className="inline-flex items-center gap-1 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium text-slate-500 transition-colors hover:bg-slate-50"
>
<X className="size-3.5" />
取消
</button>
</div>
{pwdDraft.trim() && (
<div className="mt-3 flex items-center gap-2 rounded-lg border border-slate-200/70 bg-slate-50/70 p-2">
<Link2 className="size-3.5 shrink-0 text-slate-400" />
<span className="truncate font-mono text-[11px] text-slate-500">{buildLoginLink(user, pwdDraft.trim())}</span>
<button
type="button"
onClick={() => copyText(buildLoginLink(user, pwdDraft.trim()), "已复制登录链接")}
className="ml-auto inline-flex shrink-0 items-center gap-1 rounded-md border border-slate-200 bg-white px-2 py-1 text-[11px] font-medium text-slate-500 transition-colors hover:bg-slate-50 hover:text-slate-700"
>
<Copy className="size-3" />
复制链接
</button>
</div>
)}
</div>
</li>
)}
</Fragment>
);
})}
</ul>
)}
</div>
</div>
</div>
);
}