add user management system

This commit is contained in:
qixinbo
2026-03-14 19:20:37 +08:00
parent 6c0392426e
commit 98d99ded37
15 changed files with 976 additions and 23 deletions
+73 -13
View File
@@ -1,28 +1,88 @@
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import { Sidebar } from "./components/Sidebar";
import { ChatInterface } from "./components/ChatInterface";
import { Dashboard } from "./pages/Dashboard";
import { Skills } from "./pages/Skills";
import { Settings } from "./pages/Settings";
import { Users } from "./pages/Users";
import { Login } from "./pages/Login";
import { useAuthStore } from "./store/authStore";
// Protected Route Component
function ProtectedRoute({ children, requireAdmin = false }: { children: React.ReactNode, requireAdmin?: boolean }) {
const { isAuthenticated, user } = useAuthStore();
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
if (requireAdmin && !user?.is_admin) {
return <Navigate to="/" replace />;
}
return <>{children}</>;
}
function MainLayout({ children }: { children: React.ReactNode }) {
return (
<div className="flex h-screen w-full bg-background text-foreground overflow-hidden">
<Sidebar />
<main className="flex-1 flex flex-col overflow-hidden h-screen relative">
{children}
</main>
</div>
);
}
function App() {
return (
<BrowserRouter>
<div className="flex h-screen w-full bg-background text-foreground overflow-hidden">
<Sidebar />
<main className="flex-1 flex flex-col overflow-hidden h-screen relative">
<Routes>
<Route path="/" element={
<Routes>
<Route path="/login" element={<Login />} />
{/* Protected Routes */}
<Route path="/" element={
<ProtectedRoute>
<MainLayout>
<div className="h-full overflow-hidden bg-white">
<ChatInterface />
</div>
} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/skills" element={<Skills />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</main>
</div>
</MainLayout>
</ProtectedRoute>
} />
<Route path="/dashboard" element={
<ProtectedRoute>
<MainLayout>
<Dashboard />
</MainLayout>
</ProtectedRoute>
} />
<Route path="/skills" element={
<ProtectedRoute>
<MainLayout>
<Skills />
</MainLayout>
</ProtectedRoute>
} />
<Route path="/settings" element={
<ProtectedRoute>
<MainLayout>
<Settings />
</MainLayout>
</ProtectedRoute>
} />
<Route path="/users" element={
<ProtectedRoute requireAdmin={true}>
<MainLayout>
<Users />
</MainLayout>
</ProtectedRoute>
} />
</Routes>
</BrowserRouter>
);
}
+1 -1
View File
@@ -2,7 +2,7 @@ import { useState, useRef, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { User, Loader2, Sparkles, Search, ArrowUp, ChevronDown, Database, Table, Paperclip, Bot } from "lucide-react";
import { User, Loader2, Sparkles, Search, ArrowUp, ChevronDown, Table, Paperclip } from "lucide-react";
import { api } from "@/lib/api";
import { useVisualizationStore } from "@/store/visualizationStore";
+81 -8
View File
@@ -1,8 +1,10 @@
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Menu, LayoutDashboard, Plus, MoreVertical, User, MessageSquare, Search, PanelLeftClose, Wrench, Bot } from "lucide-react";
import { useState } from "react";
import { Menu, LayoutDashboard, Plus, MoreVertical, User, Search, Wrench, Settings } from "lucide-react";
import { useState, useRef, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useAuthStore } from "@/store/authStore";
const threadItems = ["我叫", "年龄最大的是谁", "有哪些字段", "文件中有些什么字段"];
@@ -39,16 +41,36 @@ function Section({
}
function SidebarBody() {
const navigate = useNavigate();
const { user, logout } = useAuthStore();
const [showUserMenu, setShowUserMenu] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
setShowUserMenu(false);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
const handleLogout = () => {
logout();
navigate("/login");
};
return (
<div className="h-full flex flex-col bg-zinc-50/30 border-r border-zinc-200">
<div className="h-full flex flex-col bg-zinc-50/30 border-r border-zinc-200 relative">
{/* Header */}
<div className="h-14 px-4 flex items-center justify-between border-b border-zinc-100">
<div className="flex items-center gap-1.5 text-zinc-700 font-bold text-lg">
<Link to="/" className="flex items-center gap-1.5 text-zinc-700 font-bold text-lg hover:opacity-80 transition-opacity">
<span className="text-xl leading-none mr-0.5">🦞</span>
<span className="bg-clip-text text-transparent bg-gradient-to-r from-zinc-800 to-zinc-600">
</span>
</div>
</Link>
<div className="flex items-center gap-1">
<Button variant="ghost" size="icon" className="h-8 w-8 text-zinc-400 hover:text-zinc-600">
<Search className="h-4.5 w-4.5" />
@@ -60,6 +82,7 @@ function SidebarBody() {
<Button
variant="secondary"
className="w-full justify-start h-10 px-3 rounded-lg bg-zinc-200/50 hover:bg-zinc-200 text-zinc-900 font-medium"
onClick={() => navigate("/dashboard")}
>
<LayoutDashboard className="h-4.5 w-4.5 mr-2 text-zinc-600" />
Dashboard
@@ -68,6 +91,7 @@ function SidebarBody() {
<Button
variant="outline"
className="w-full justify-start h-10 px-3 rounded-lg border-zinc-200 bg-white hover:bg-zinc-50 text-zinc-600 shadow-sm font-medium"
onClick={() => navigate("/")}
>
<Plus className="h-4 w-4 mr-2" />
New Thread
@@ -78,12 +102,18 @@ function SidebarBody() {
<Section title="THREADS" count={threadItems.length} items={threadItems} />
</ScrollArea>
<div className="p-4 border-t border-zinc-200 mt-auto">
<div className="p-4 border-t border-zinc-200 mt-auto relative" ref={menuRef}>
<div className="flex items-center justify-between text-zinc-600">
<button className="flex items-center gap-2 hover:text-zinc-900 transition-colors">
<div className="w-8 h-8 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600 border border-indigo-200">
<button
className="flex items-center gap-2 hover:text-zinc-900 transition-colors p-1 rounded-full hover:bg-zinc-100"
onClick={() => setShowUserMenu(!showUserMenu)}
>
<div className="w-8 h-8 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600 border border-indigo-200 shadow-sm">
<User className="h-4.5 w-4.5" />
</div>
<div className="text-sm font-medium truncate max-w-[100px] text-left">
{user?.username || 'User'}
</div>
</button>
<button className="flex items-center gap-1.5 text-sm hover:text-zinc-900 transition-colors px-2 py-1.5 rounded-md hover:bg-zinc-100">
@@ -91,6 +121,49 @@ function SidebarBody() {
</button>
</div>
{/* User Settings Popover Menu */}
{showUserMenu && (
<div className="absolute bottom-[72px] left-4 w-56 bg-white rounded-xl shadow-xl border border-zinc-200 py-1.5 z-50 overflow-hidden animate-in fade-in zoom-in duration-200">
<div className="px-3 py-2 border-b border-zinc-100 mb-1">
<p className="text-sm font-medium text-zinc-900 truncate">{user?.username}</p>
<p className="text-xs text-zinc-500 truncate">{user?.email}</p>
</div>
<button
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-zinc-700 hover:bg-zinc-100 transition-colors"
onClick={() => {
navigate("/settings");
setShowUserMenu(false);
}}
>
<Settings className="h-4 w-4 text-zinc-500" />
Settings
</button>
{user?.is_admin && (
<button
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-indigo-600 hover:bg-indigo-50 transition-colors"
onClick={() => {
navigate("/users");
setShowUserMenu(false);
}}
>
<User className="h-4 w-4" />
User Management
</button>
)}
<div className="h-px bg-zinc-100 my-1 mx-2" />
<button
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors"
onClick={handleLogout}
>
Log out
</button>
</div>
)}
</div>
</div>
);
+164
View File
@@ -0,0 +1,164 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Loader2 } from "lucide-react";
import { api } from "@/lib/api";
import { useAuthStore } from "@/store/authStore";
export function Login() {
const [isLogin, setIsLogin] = useState(true);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
const navigate = useNavigate();
const login = useAuthStore((state) => state.login);
const [formData, setFormData] = useState({
username: "",
email: "",
password: "",
});
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
setIsLoading(true);
try {
if (isLogin) {
// Handle Login using application/x-www-form-urlencoded as required by OAuth2PasswordRequestForm
const params = new URLSearchParams();
params.append("username", formData.username);
params.append("password", formData.password);
const response = await fetch("/api/v1/auth/login", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: params,
});
if (!response.ok) {
const errData = await response.json();
throw new Error(errData.detail || "Login failed");
}
const data = await response.json();
login(data.user, data.access_token);
navigate("/");
} else {
// Handle Registration
await api.post("/api/v1/auth/register", {
username: formData.username,
email: formData.email,
password: formData.password,
});
// Auto login after successful registration
setIsLogin(true);
setError("Registration successful! Please login.");
}
} catch (err: any) {
setError(err.message || "An error occurred");
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-screen flex flex-col items-center justify-center bg-zinc-50 px-4">
<div className="w-full max-w-md">
<div className="mb-10 text-center flex flex-col items-center gap-4 select-none">
<div className="text-[56px] leading-none animate-bounce-slow pb-2">
🦞
</div>
<h1 className="text-[40px] font-bold bg-clip-text text-transparent bg-gradient-to-r from-red-500 via-orange-500 to-amber-500 tracking-tight">
DataClaw
</h1>
</div>
<div className="bg-white rounded-2xl shadow-xl border border-zinc-100 p-8">
<h2 className="text-2xl font-bold text-zinc-800 mb-6 text-center">
{isLogin ? "Welcome Back" : "Create Account"}
</h2>
{error && (
<div className={`p-3 rounded-lg mb-6 text-sm ${error.includes("successful") ? "bg-emerald-50 text-emerald-600" : "bg-red-50 text-red-600"}`}>
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-5">
<div className="space-y-2">
<Label htmlFor="username">Username</Label>
<Input
id="username"
type="text"
placeholder="Enter your username"
value={formData.username}
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
required
className="h-11"
/>
</div>
{!isLogin && (
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="Enter your email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
required
className="h-11"
/>
</div>
)}
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
placeholder="Enter your password"
value={formData.password}
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
required
className="h-11"
/>
</div>
<Button
type="submit"
disabled={isLoading || !formData.username || !formData.password || (!isLogin && !formData.email)}
className="w-full h-11 bg-indigo-600 hover:bg-indigo-700 text-white font-medium text-base rounded-xl transition-all shadow-md"
>
{isLoading ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
isLogin ? "Sign In" : "Sign Up"
)}
</Button>
</form>
<div className="mt-6 text-center text-sm text-zinc-500">
{isLogin ? "Don't have an account?" : "Already have an account?"}
<button
onClick={() => {
setIsLogin(!isLogin);
setError("");
}}
className="ml-2 font-medium text-indigo-600 hover:text-indigo-700 transition-colors"
>
{isLogin ? "Sign Up" : "Sign In"}
</button>
</div>
</div>
</div>
</div>
);
}
+266
View File
@@ -0,0 +1,266 @@
import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Pencil, Trash2, Plus, Users as UsersIcon, Loader2 } from "lucide-react";
import { api } from "@/lib/api";
interface User {
id: number;
username: string;
email: string;
is_active: boolean;
is_admin: boolean;
created_at: string;
}
export function Users() {
const [users, setUsers] = useState<User[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [editingUser, setEditingUser] = useState<User | null>(null);
const [formData, setFormData] = useState({
username: "",
email: "",
password: "",
is_active: true,
is_admin: false,
});
const [error, setError] = useState("");
const fetchUsers = async () => {
try {
setIsLoading(true);
const data = await api.get<User[]>("/api/v1/users");
setUsers(data);
} catch (err) {
console.error("Failed to fetch users", err);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchUsers();
}, []);
const handleOpenDialog = (user?: User) => {
setError("");
if (user) {
setEditingUser(user);
setFormData({
username: user.username,
email: user.email,
password: "", // Don't show password
is_active: user.is_active,
is_admin: user.is_admin,
});
} else {
setEditingUser(null);
setFormData({
username: "",
email: "",
password: "",
is_active: true,
is_admin: false,
});
}
setIsDialogOpen(true);
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
try {
if (editingUser) {
// Update
await api.put(`/api/v1/users/${editingUser.id}`, {
username: formData.username,
email: formData.email,
is_active: formData.is_active,
is_admin: formData.is_admin,
});
} else {
// Create
if (!formData.password) {
setError("Password is required for new users");
return;
}
await api.post("/api/v1/users", formData);
}
setIsDialogOpen(false);
fetchUsers();
} catch (err: any) {
setError(err.message || "An error occurred");
}
};
const handleDelete = async (id: number) => {
if (window.confirm("Are you sure you want to delete this user?")) {
try {
await api.delete(`/api/v1/users/${id}`);
fetchUsers();
} catch (err) {
console.error("Failed to delete user", err);
}
}
};
return (
<div className="flex-1 flex flex-col h-full bg-zinc-50/30 overflow-hidden">
<div className="h-14 px-6 flex items-center justify-between border-b border-zinc-100 bg-white">
<div className="flex items-center gap-2 text-zinc-700 font-medium">
<UsersIcon className="h-5 w-5 text-indigo-500" />
User Management
</div>
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogTrigger className="inline-flex items-center justify-center gap-1.5 whitespace-nowrap text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-8 bg-indigo-600 hover:bg-indigo-700 text-white rounded-md px-3" onClick={() => handleOpenDialog()}>
<Plus className="h-4 w-4" />
Add User
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<form onSubmit={handleSubmit}>
<DialogHeader>
<DialogTitle>{editingUser ? "Edit User" : "Add New User"}</DialogTitle>
</DialogHeader>
<div className="grid gap-4 py-4">
{error && <div className="text-red-500 text-sm">{error}</div>}
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<Input
id="username"
value={formData.username}
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
required
/>
</div>
<div className="grid gap-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
required
/>
</div>
{!editingUser && (
<div className="grid gap-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
value={formData.password}
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
required
/>
</div>
)}
<div className="flex items-center justify-between">
<Label htmlFor="is_active">Active</Label>
<Switch
id="is_active"
checked={formData.is_active}
onCheckedChange={(checked) => setFormData({ ...formData, is_active: checked })}
/>
</div>
<div className="flex items-center justify-between">
<Label htmlFor="is_admin">Admin</Label>
<Switch
id="is_admin"
checked={formData.is_admin}
onCheckedChange={(checked) => setFormData({ ...formData, is_admin: checked })}
/>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>
Cancel
</Button>
<Button type="submit" className="bg-indigo-600 hover:bg-indigo-700 text-white">
Save
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</div>
<div className="flex-1 p-6 overflow-auto">
<div className="bg-white rounded-xl border border-zinc-200 shadow-sm overflow-hidden">
{isLoading ? (
<div className="flex items-center justify-center h-40">
<Loader2 className="h-6 w-6 animate-spin text-zinc-400" />
</div>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Username</TableHead>
<TableHead>Email</TableHead>
<TableHead>Status</TableHead>
<TableHead>Role</TableHead>
<TableHead>Created At</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{users.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-center h-24 text-zinc-500">
No users found.
</TableCell>
</TableRow>
) : (
users.map((user) => (
<TableRow key={user.id}>
<TableCell className="font-medium">{user.id}</TableCell>
<TableCell>{user.username}</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>
<span className={`inline-flex px-2 py-1 rounded-full text-xs font-medium ${user.is_active ? 'bg-emerald-100 text-emerald-700' : 'bg-zinc-100 text-zinc-600'}`}>
{user.is_active ? 'Active' : 'Inactive'}
</span>
</TableCell>
<TableCell>
<span className={`inline-flex px-2 py-1 rounded-full text-xs font-medium ${user.is_admin ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700'}`}>
{user.is_admin ? 'Admin' : 'User'}
</span>
</TableCell>
<TableCell className="text-zinc-500">
{new Date(user.created_at).toLocaleDateString()}
</TableCell>
<TableCell className="text-right">
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-zinc-500 hover:text-indigo-600"
onClick={() => handleOpenDialog(user)}
>
<Pencil className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-zinc-500 hover:text-red-600"
onClick={() => handleDelete(user.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
)}
</div>
</div>
</div>
);
}
+32
View File
@@ -0,0 +1,32 @@
import { create } from 'zustand';
export interface User {
id: number;
username: string;
email: string;
is_admin: boolean;
}
interface AuthState {
user: User | null;
token: string | null;
isAuthenticated: boolean;
login: (user: User, token: string) => void;
logout: () => void;
}
export const useAuthStore = create<AuthState>((set) => ({
user: JSON.parse(localStorage.getItem('user') || 'null'),
token: localStorage.getItem('token'),
isAuthenticated: !!localStorage.getItem('token'),
login: (user, token) => {
localStorage.setItem('user', JSON.stringify(user));
localStorage.setItem('token', token);
set({ user, token, isAuthenticated: true });
},
logout: () => {
localStorage.removeItem('user');
localStorage.removeItem('token');
set({ user: null, token: null, isAuthenticated: false });
},
}));