Add local user authentication and admin capabilities
Implement local user authentication with password hashing, add admin roles for user management and audit log viewing, and introduce audit logging for critical actions. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 776963d0-f75d-42e2-a57b-cc36bdff8495 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Event-Id: 832a44ff-12ae-4096-8a0d-666ec083d536 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/0683fb79-a27c-485c-9333-5f4b288c4567/776963d0-f75d-42e2-a57b-cc36bdff8495/1p7jhzu Replit-Helium-Checkpoint-Created: true
This commit is contained in:
@@ -0,0 +1,350 @@
|
||||
import { useState } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import {
|
||||
useListUsers,
|
||||
useCreateUser,
|
||||
useUpdateUser,
|
||||
useDeleteUser,
|
||||
useListAuditLogs,
|
||||
getListUsersQueryKey,
|
||||
getListAuditLogsQueryKey,
|
||||
} from "@workspace/api-client-react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { Layout } from "@/components/layout";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Users, ScrollText, ShieldAlert, Plus, Pencil, Trash2, Clock } from "lucide-react";
|
||||
import { format } from "date-fns";
|
||||
|
||||
export default function Admin() {
|
||||
const [, setLocation] = useLocation();
|
||||
const { user, isAdmin, isLoading: authLoading } = useAuth();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [editUser, setEditUser] = useState<{ id: number; username: string; role: string } | null>(null);
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<{ id: number; username: string } | null>(null);
|
||||
|
||||
const [newUsername, setNewUsername] = useState("");
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [newEmail, setNewEmail] = useState("");
|
||||
const [newRole, setNewRole] = useState<"admin" | "user">("user");
|
||||
|
||||
const { data: users, isLoading: loadingUsers } = useListUsers({
|
||||
query: { queryKey: getListUsersQueryKey(), enabled: isAdmin },
|
||||
});
|
||||
const { data: auditLogs, isLoading: loadingLogs } = useListAuditLogs(
|
||||
{ limit: 100 },
|
||||
{ query: { queryKey: getListAuditLogsQueryKey({ limit: 100 }), enabled: isAdmin } },
|
||||
);
|
||||
|
||||
const createUser = useCreateUser();
|
||||
const updateUser = useUpdateUser();
|
||||
const deleteUser = useDeleteUser();
|
||||
|
||||
if (!authLoading && !isAdmin) {
|
||||
return (
|
||||
<Layout>
|
||||
<div className="flex flex-col items-center justify-center py-20 gap-4">
|
||||
<ShieldAlert className="w-12 h-12 text-muted-foreground" />
|
||||
<h2 className="text-2xl font-bold">Admin Access Required</h2>
|
||||
<p className="text-muted-foreground">You need admin rights to view this page.</p>
|
||||
<Button variant="outline" onClick={() => setLocation("/")}>Go Home</Button>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
||||
const handleCreateUser = () => {
|
||||
if (!newUsername || !newPassword) return;
|
||||
createUser.mutate(
|
||||
{ data: { username: newUsername, password: newPassword, email: newEmail || undefined, role: newRole } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast({ title: "User created", description: `${newUsername} has been created.` });
|
||||
queryClient.invalidateQueries({ queryKey: getListUsersQueryKey() });
|
||||
setCreateOpen(false);
|
||||
setNewUsername("");
|
||||
setNewPassword("");
|
||||
setNewEmail("");
|
||||
setNewRole("user");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast({ title: "Failed to create user", description: err.data?.error ?? err.message, variant: "destructive" });
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const handleUpdateRole = (role: "admin" | "user") => {
|
||||
if (!editUser) return;
|
||||
updateUser.mutate(
|
||||
{ id: editUser.id, data: { role } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast({ title: "Role updated" });
|
||||
queryClient.invalidateQueries({ queryKey: getListUsersQueryKey() });
|
||||
setEditUser(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast({ title: "Failed to update role", description: err.data?.error ?? err.message, variant: "destructive" });
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const handleDeleteUser = () => {
|
||||
if (!deleteConfirm) return;
|
||||
deleteUser.mutate(
|
||||
{ id: deleteConfirm.id },
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast({ title: "User deleted", description: `${deleteConfirm.username} has been removed.` });
|
||||
queryClient.invalidateQueries({ queryKey: getListUsersQueryKey() });
|
||||
setDeleteConfirm(null);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast({ title: "Failed to delete user", description: (err.data as { error?: string } | null)?.error ?? err.message, variant: "destructive" });
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
function actionBadgeVariant(action: string): "default" | "secondary" | "destructive" | "outline" {
|
||||
if (action === "create") return "default";
|
||||
if (action === "delete") return "destructive";
|
||||
return "secondary";
|
||||
}
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="space-y-6 pb-10">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight mb-2">Admin Panel</h1>
|
||||
<p className="text-muted-foreground">Manage users and review system changes.</p>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="users">
|
||||
<TabsList className="mb-4">
|
||||
<TabsTrigger value="users" className="gap-2">
|
||||
<Users className="w-4 h-4" /> Users
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="audit" className="gap-2">
|
||||
<ScrollText className="w-4 h-4" /> Audit Log
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="users">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>Local Users</CardTitle>
|
||||
<CardDescription>Manage accounts for local authentication.</CardDescription>
|
||||
</div>
|
||||
<Button size="sm" onClick={() => setCreateOpen(true)}>
|
||||
<Plus className="w-4 h-4 mr-2" /> Add User
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingUsers ? (
|
||||
<div className="space-y-3">
|
||||
{[1, 2, 3].map((i) => <Skeleton key={i} className="h-12 w-full" />)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{users?.map((u) => (
|
||||
<div key={u.id} className="flex items-center justify-between py-3 gap-4">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center shrink-0 font-medium text-primary text-sm">
|
||||
{u.username.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="font-medium text-sm truncate">{u.username}</p>
|
||||
{u.email && <p className="text-xs text-muted-foreground truncate">{u.email}</p>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<Badge variant={u.role === "admin" ? "default" : "secondary"}>
|
||||
{u.role}
|
||||
</Badge>
|
||||
{u.username !== user?.preferredUsername && (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => setEditUser({ id: u.id, username: u.username, role: u.role })}
|
||||
>
|
||||
<Pencil className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => setDeleteConfirm({ id: u.id, username: u.username })}
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{(!users || users.length === 0) && (
|
||||
<p className="text-sm text-muted-foreground py-4 text-center">No users yet.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="audit">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Audit Log</CardTitle>
|
||||
<CardDescription>All create, update and delete operations tracked by the system.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loadingLogs ? (
|
||||
<div className="space-y-3">
|
||||
{[1, 2, 3, 4, 5].map((i) => <Skeleton key={i} className="h-14 w-full" />)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{auditLogs?.map((log) => (
|
||||
<div key={log.id} className="py-3 space-y-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Badge variant={actionBadgeVariant(log.action)} className="capitalize text-xs">
|
||||
{log.action}
|
||||
</Badge>
|
||||
<span className="text-sm font-medium capitalize">{log.entityType}</span>
|
||||
{log.entityId && (
|
||||
<span className="text-sm text-muted-foreground">#{log.entityId}</span>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground ml-auto flex items-center gap-1">
|
||||
<Clock className="w-3 h-3" />
|
||||
{format(new Date(log.createdAt), "dd.MM.yyyy HH:mm")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>by <span className="font-medium text-foreground">{log.username}</span></span>
|
||||
{log.changes && (
|
||||
<span className="truncate max-w-[400px] font-mono bg-muted px-1.5 py-0.5 rounded text-[11px]">
|
||||
{log.changes.length > 120 ? log.changes.slice(0, 120) + "…" : log.changes}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{(!auditLogs || auditLogs.length === 0) && (
|
||||
<p className="text-sm text-muted-foreground py-4 text-center">No audit entries yet.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create New User</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="space-y-2">
|
||||
<Label>Username</Label>
|
||||
<Input value={newUsername} onChange={(e) => setNewUsername(e.target.value)} placeholder="username" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Password</Label>
|
||||
<Input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} placeholder="min. 6 characters" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Email (Optional)</Label>
|
||||
<Input type="email" value={newEmail} onChange={(e) => setNewEmail(e.target.value)} placeholder="user@example.com" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Role</Label>
|
||||
<Select value={newRole} onValueChange={(v) => setNewRole(v as "admin" | "user")}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="user">User</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setCreateOpen(false)}>Cancel</Button>
|
||||
<Button onClick={handleCreateUser} disabled={createUser.isPending || !newUsername || !newPassword}>
|
||||
{createUser.isPending ? "Creating…" : "Create User"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={!!editUser} onOpenChange={(open) => !open && setEditUser(null)}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Change Role — {editUser?.username}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="py-2">
|
||||
<Select
|
||||
value={editUser?.role || "user"}
|
||||
onValueChange={(v) => setEditUser(editUser ? { ...editUser, role: v } : null)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="user">User</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setEditUser(null)}>Cancel</Button>
|
||||
<Button
|
||||
onClick={() => handleUpdateRole(editUser?.role as "admin" | "user")}
|
||||
disabled={updateUser.isPending}
|
||||
>
|
||||
Save
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={!!deleteConfirm} onOpenChange={(open) => !open && setDeleteConfirm(null)}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete User</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-muted-foreground py-2">
|
||||
Are you sure you want to delete <span className="font-medium text-foreground">{deleteConfirm?.username}</span>? This cannot be undone.
|
||||
</p>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDeleteConfirm(null)}>Cancel</Button>
|
||||
<Button variant="destructive" onClick={handleDeleteUser} disabled={deleteUser.isPending}>
|
||||
{deleteUser.isPending ? "Deleting…" : "Delete"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user