🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
feat: update middleware and layout for admin route handling (#276)
Bill Yangd46b93106ab1
diff --git a/client/src/app/admin/page.tsx b/client/src/app/admin/page.tsxnew file mode 100644index 000000000..e39f2dfac--- /dev/null+++ b/client/src/app/admin/page.tsx@@ -0,0 +1,212 @@+"use client";++import { useEffect, useState } from "react";+import { useRouter } from "next/navigation";+import { Button } from "@/components/ui/button";+import { AlertCircle } from "lucide-react";+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";+import { StandardPage } from "@/components/StandardPage";+import { useAdminUsers } from "@/hooks/useAdminUsers";+import { UsersTable } from "@/components/admin/UsersTable";+import { UserFilters } from "@/components/admin/UserFilters";+import { UserTablePagination } from "@/components/admin/UserTablePagination";+import { authClient } from "@/lib/auth";++export default function AdminPage() {+ const router = useRouter();+ const [isAdmin, setIsAdmin] = useState(false);+ const [isImpersonating, setIsImpersonating] = useState(false);+ const [isCheckingAdmin, setIsCheckingAdmin] = useState(true);++ const {+ // Data+ users,+ total,++ // Loading state+ isLoading,+ isError,++ // Table state+ sorting,+ setSorting,+ columnFilters,+ setColumnFilters,+ pagination,+ setPagination,+ globalFilter,+ setGlobalFilter,++ // Actions+ handleImpersonate,+ } = useAdminUsers();++ useEffect(() => {+ async function checkAdminPermission() {+ try {+ // Check if the user has impersonate permission (admin feature)+ const result = await authClient.admin.hasPermission({+ permissions: {+ user: ["impersonate"],+ },+ });+ setIsAdmin(result.data?.success ?? false);++ // Check if the user is currently impersonating+ const session = await authClient.getSession();+ // Check if impersonatedBy exists in the session data+ setIsImpersonating(Boolean(session.data?.session?.impersonatedBy));++ setIsCheckingAdmin(false);+ } catch (err) {+ setIsAdmin(false);+ setIsCheckingAdmin(false);+ console.error("Error checking admin status:", err);+ }+ }++ checkAdminPermission();+ }, []);++ // Function to stop impersonating+ const stopImpersonating = async () => {+ try {+ await authClient.admin.stopImpersonating();+ setIsImpersonating(false);+ window.location.reload();+ return true;+ } catch (err) {+ const errorMessage =+ err instanceof Error ? err.message : "Unknown error occurred";+ console.error(`Failed to stop impersonation: ${errorMessage}`);+ return false;+ }+ };++ const data = { users, total };++ // Handle impersonation with navigation+ const onImpersonate = async (userId: string) => {+ const success = await handleImpersonate(userId);+ if (success) {+ router.push("/");+ }+ };++ // If not admin, show access denied+ if (!isAdmin && !isCheckingAdmin) {+ return (+ <div className="container mt-8">+ <Alert variant="destructive">+ <AlertCircle className="h-4 w-4" />+ <AlertTitle>Access Denied</AlertTitle>+ <AlertDescription>+ You don't have permission to access this page. Please contact an+ administrator if you believe this is an error.+ </AlertDescription>+ </Alert>+ </div>+ );+ }++ return (+ <StandardPage>+ <div className="flex items-center justify-between mb-6">+ <h1 className="text-2xl font-bold">Admin Dashboard</h1>+ {isImpersonating && (+ <Button onClick={stopImpersonating} variant="destructive">+ Stop Impersonating+ </Button>+ )}+ </div>++ {isError && (+ <Alert variant="destructive" className="mb-4">+ <AlertCircle className="h-4 w-4" />+ <AlertTitle>Error</AlertTitle>+ <AlertDescription>+ Failed to load users. Please try again later.+ </AlertDescription>+ </Alert>+ )}++ <div className="space-y-4">+ {/* Filters */}+ <UserFilters+ table={+ {+ getColumn: (columnId: string) => {+ const getFilterValue = () =>+ columnFilters.find((filter) => filter.id === columnId)+ ?.value ?? "";++ const setFilterValue = (value: string) => {+ const newFilters = columnFilters.filter(+ (filter) => filter.id !== columnId+ );+ if (value) {+ newFilters.push({ id: columnId, value });+ }+ setColumnFilters(newFilters);+ };++ return {+ getFilterValue,+ setFilterValue,+ };+ },+ } as any+ }+ />++ {/* Users Table */}+ <UsersTable+ data={data}+ isLoading={isLoading}+ pagination={pagination}+ setPagination={setPagination}+ sorting={sorting}+ setSorting={setSorting}+ columnFilters={columnFilters}+ setColumnFilters={setColumnFilters}+ globalFilter={globalFilter}+ setGlobalFilter={setGlobalFilter}+ onImpersonate={onImpersonate}+ />++ {/* Pagination */}+ <UserTablePagination+ table={+ {+ getCanPreviousPage: () => pagination.pageIndex > 0,+ getCanNextPage: () =>+ pagination.pageIndex <+ Math.ceil(total / pagination.pageSize) - 1,+ getPageCount: () => Math.ceil(total / pagination.pageSize),+ getState: () => ({ pagination }),+ setPageIndex: (index: number) =>+ setPagination({ ...pagination, pageIndex: index }),+ previousPage: () =>+ setPagination({+ ...pagination,+ pageIndex: Math.max(0, pagination.pageIndex - 1),+ }),+ nextPage: () =>+ setPagination({+ ...pagination,+ pageIndex: Math.min(+ Math.ceil(total / pagination.pageSize) - 1,+ pagination.pageIndex + 1+ ),+ }),+ } as any+ }+ data={data}+ pagination={pagination}+ setPagination={setPagination}+ isLoading={isLoading}+ />+ </div>+ </StandardPage>+ );+}diff --git a/client/src/app/layout.tsx b/client/src/app/layout.tsxindex 1267f2263..43069ec33 100644--- a/client/src/app/layout.tsx+++ b/client/src/app/layout.tsx@@ -11,6 +11,7 @@ import { userStore } from "../lib/userStore";import { cn } from "../lib/utils";import "./globals.css";import Script from "next/script";+import { useStopImpersonation } from "@/hooks/useStopImpersonation";const inter = Inter({ subsets: ["latin"] });@@ -40,6 +41,9 @@ export default function RootLayout({const [isCheckingPublic, setIsCheckingPublic] = useState(false);const [isPublicSite, setIsPublicSite] = useState(false);+ // Use the hook to expose stopImpersonating globally+ useStopImpersonation();+useEffect(() => {// Check if the current path could be a site path// Extract potential siteId from path like /{siteId} or /{siteId}/something@@ -50,9 +54,14 @@ export default function RootLayout({// Don't check for public site status on obvious non-site pathsif (!publicRoutes.includes(`/${potentialSiteId}`) &&- !["_next", "api", "settings", "subscribe", "invitation"].includes(- potentialSiteId- )+ ![+ "_next",+ "api",+ "settings",+ "subscribe",+ "invitation",+ "admin",+ ].includes(potentialSiteId)) {setIsCheckingPublic(true);diff --git a/client/src/components/TopBar.tsx b/client/src/components/TopBar.tsxindex 08c850ff5..58d81fdc2 100644--- a/client/src/components/TopBar.tsx+++ b/client/src/components/TopBar.tsx@@ -52,6 +52,11 @@ export function TopBar() {>Sign out</DropdownMenuItem>+ {session.data.user.role === "admin" && (+ <Link href="/admin" passHref>+ <DropdownMenuItem>Admin</DropdownMenuItem>+ </Link>+ )}</DropdownMenuContent></DropdownMenu>) : IS_DEMO ? (diff --git a/client/src/components/admin/UserFilters.tsx b/client/src/components/admin/UserFilters.tsxnew file mode 100644index 000000000..f4218c1a0--- /dev/null+++ b/client/src/components/admin/UserFilters.tsx@@ -0,0 +1,56 @@+"use client";++import { Search } from "lucide-react";+import { Table } from "@tanstack/react-table";+import { AdminUser } from "@/types/admin";+import { Input } from "@/components/ui/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";++interface UserFiltersProps {+ table: Table<AdminUser>;+}++export function UserFilters({ table }: UserFiltersProps) {+ return (+ <div className="flex flex-col md:flex-row gap-4">+ <div className="relative flex-1">+ <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-neutral-400" />+ <Input+ placeholder="Filter by email..."+ value={(table.getColumn("email")?.getFilterValue() as string) ?? ""}+ onChange={(e) =>+ table.getColumn("email")?.setFilterValue(e.target.value)+ }+ className="pl-9 bg-neutral-900 border-neutral-700"+ />+ </div>+ <div className="w-full md:w-48">+ <Select+ value={(table.getColumn("role")?.getFilterValue() as string) ?? ""}+ onValueChange={(value) => {+ if (value === "all") {+ table.getColumn("role")?.setFilterValue("");+ } else {+ table.getColumn("role")?.setFilterValue(value);+ }+ }}+ >+ <SelectTrigger>+ <SelectValue placeholder="Filter by role" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">All Roles</SelectItem>+ <SelectItem value="admin">Admin</SelectItem>+ <SelectItem value="user">User</SelectItem>+ </SelectContent>+ </Select>+ </div>+ </div>+ );+}diff --git a/client/src/components/admin/UserTablePagination.tsx b/client/src/components/admin/UserTablePagination.tsxnew file mode 100644index 000000000..45b073ca4--- /dev/null+++ b/client/src/components/admin/UserTablePagination.tsx@@ -0,0 +1,135 @@+"use client";++import { Table } from "@tanstack/react-table";+import { AdminUser } from "@/types/admin";+import { Button } from "@/components/ui/button";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import {+ ChevronLeft,+ ChevronRight,+ ChevronsLeft,+ ChevronsRight,+} from "lucide-react";++interface PaginationProps {+ table: Table<AdminUser>;+ data: { users: AdminUser[]; total: number } | undefined;+ pagination: { pageIndex: number; pageSize: number };+ setPagination: (value: { pageIndex: number; pageSize: number }) => void;+ isLoading: boolean;+}++export function UserTablePagination({+ table,+ data,+ pagination,+ setPagination,+ isLoading,+}: PaginationProps) {+ return (+ <div className="flex items-center justify-between">+ <div className="text-sm text-neutral-400">+ {isLoading ? (+ <span>Loading users...</span>+ ) : (+ <>+ Showing{" "}+ <span className="font-semibold">+ {data?.users?.length+ ? pagination.pageIndex * pagination.pageSize + 1+ : 0}+ </span>{" "}+ to{" "}+ <span className="font-semibold">+ {data?.users?.length+ ? Math.min(+ (pagination.pageIndex + 1) * pagination.pageSize,+ data?.total || 0+ )+ : 0}+ </span>{" "}+ of <span className="font-semibold">{data?.total || 0}</span> users+ </>+ )}+ </div>+ <div className="flex items-center space-x-2">+ <div className="mr-4 flex items-center space-x-2">+ <span className="text-sm text-neutral-400">Page size:</span>+ <Select+ value={pagination.pageSize.toString()}+ onValueChange={(value) => {+ setPagination({+ pageIndex: 0, // Reset to first page when changing page size+ pageSize: Number(value),+ });+ }}+ >+ <SelectTrigger className="h-8 w-16">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="10">10</SelectItem>+ <SelectItem value="25">25</SelectItem>+ <SelectItem value="50">50</SelectItem>+ <SelectItem value="100">100</SelectItem>+ </SelectContent>+ </Select>+ </div>+ <Button+ variant="outline"+ size="sm"+ onClick={() => table.setPageIndex(0)}+ disabled={!table.getCanPreviousPage() || isLoading}+ >+ <ChevronsLeft className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={() => table.previousPage()}+ disabled={!table.getCanPreviousPage() || isLoading}+ >+ <ChevronLeft className="h-4 w-4" />+ </Button>+ <div className="text-sm text-neutral-400">+ {isLoading ? (+ <span>Loading...</span>+ ) : (+ <>+ Page{" "}+ <span className="font-semibold">+ {table.getState().pagination.pageIndex + 1}+ </span>{" "}+ of{" "}+ <span className="font-semibold">+ {Math.max(table.getPageCount(), 1)}+ </span>+ </>+ )}+ </div>+ <Button+ variant="outline"+ size="sm"+ onClick={() => table.nextPage()}+ disabled={!table.getCanNextPage() || isLoading}+ >+ <ChevronRight className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={() => table.setPageIndex(table.getPageCount() - 1)}+ disabled={!table.getCanNextPage() || isLoading}+ >+ <ChevronsRight className="h-4 w-4" />+ </Button>+ </div>+ </div>+ );+}diff --git a/client/src/components/admin/UserTableSkeleton.tsx b/client/src/components/admin/UserTableSkeleton.tsxnew file mode 100644index 000000000..ffc9fa480--- /dev/null+++ b/client/src/components/admin/UserTableSkeleton.tsx@@ -0,0 +1,43 @@+"use client";++import { TableCell, TableRow } from "@/components/ui/table";++interface SkeletonProps {+ rowCount?: number;+ columnCount?: number;+}++export function UserTableSkeleton({ rowCount = 50 }: SkeletonProps) {+ return (+ <>+ {Array.from({ length: rowCount }).map((_, index) => (+ <TableRow key={index} className="animate-pulse">+ {/* User ID column */}+ <TableCell>+ <div className="h-6 bg-neutral-800 rounded w-32 font-mono"></div>+ </TableCell>+ {/* Name column */}+ <TableCell>+ <div className="h-6 bg-neutral-800 rounded w-24"></div>+ </TableCell>+ {/* Email column */}+ <TableCell>+ <div className="h-6 bg-neutral-800 rounded w-48"></div>+ </TableCell>+ {/* Role column */}+ <TableCell>+ <div className="h-6 bg-neutral-800 rounded w-16"></div>+ </TableCell>+ {/* Created At column */}+ <TableCell>+ <div className="h-6 bg-neutral-800 rounded w-24"></div>+ </TableCell>+ {/* Action column */}+ <TableCell>+ <div className="h-8 bg-neutral-800 rounded w-28"></div>+ </TableCell>+ </TableRow>+ ))}+ </>+ );+}diff --git a/client/src/components/admin/UsersTable.tsx b/client/src/components/admin/UsersTable.tsxnew file mode 100644index 000000000..c50fdf8cc--- /dev/null+++ b/client/src/components/admin/UsersTable.tsx@@ -0,0 +1,252 @@+"use client";++import { useMemo } from "react";+import { AdminUser } from "@/types/admin";+import { User } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ ColumnDef,+ flexRender,+ getCoreRowModel,+ useReactTable,+ getPaginationRowModel,+ getSortedRowModel,+ getFilteredRowModel,+ SortingState,+ ColumnFiltersState,+} from "@tanstack/react-table";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";+import { UserTableSkeleton } from "./UserTableSkeleton";+import { userStore } from "@/lib/userStore";+import { ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";++interface UsersTableProps {+ data: { users: AdminUser[]; total: number } | undefined;+ isLoading: boolean;+ pagination: { pageIndex: number; pageSize: number };+ setPagination: (value: { pageIndex: number; pageSize: number }) => void;+ sorting: SortingState;+ setSorting: (sorting: SortingState) => void;+ columnFilters: ColumnFiltersState;+ setColumnFilters: (filters: ColumnFiltersState) => void;+ globalFilter: string;+ setGlobalFilter: (filter: string) => void;+ onImpersonate: (userId: string) => void;+}++export function UsersTable({+ data,+ isLoading,+ pagination,+ setPagination,+ sorting,+ setSorting,+ columnFilters,+ setColumnFilters,+ globalFilter,+ setGlobalFilter,+ onImpersonate,+}: UsersTableProps) {+ // Define columns for the table+ const columns = useMemo<ColumnDef<AdminUser>[]>(+ () => [+ {+ accessorKey: "id",+ header: ({ column }) => (+ <Button+ variant="ghost"+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}+ className="p-0 hover:bg-transparent"+ >+ User ID+ {{+ asc: <ArrowUp className="ml-2 h-4 w-4" />,+ desc: <ArrowDown className="ml-2 h-4 w-4" />,+ }[column.getIsSorted() as string] ?? (+ <ArrowUpDown className="ml-2 h-4 w-4" />+ )}+ </Button>+ ),+ cell: ({ row }) => (+ <div className="font-mono">{row.getValue("id")}</div>+ ),+ },+ {+ accessorKey: "name",+ header: ({ column }) => (+ <Button+ variant="ghost"+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}+ className="p-0 hover:bg-transparent"+ >+ Name+ {{+ asc: <ArrowUp className="ml-2 h-4 w-4" />,+ desc: <ArrowDown className="ml-2 h-4 w-4" />,+ }[column.getIsSorted() as string] ?? (+ <ArrowUpDown className="ml-2 h-4 w-4" />+ )}+ </Button>+ ),+ cell: ({ row }) => row.getValue("name") || "N/A",+ },+ {+ accessorKey: "email",+ header: ({ column }) => (+ <Button+ variant="ghost"+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}+ className="p-0 hover:bg-transparent"+ >+ {{+ asc: <ArrowUp className="ml-2 h-4 w-4" />,+ desc: <ArrowDown className="ml-2 h-4 w-4" />,+ }[column.getIsSorted() as string] ?? (+ <ArrowUpDown className="ml-2 h-4 w-4" />+ )}+ </Button>+ ),+ cell: ({ row }) => row.getValue("email"),+ },+ {+ accessorKey: "role",+ header: ({ column }) => (+ <Button+ variant="ghost"+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}+ className="p-0 hover:bg-transparent"+ >+ Role+ {{+ asc: <ArrowUp className="ml-2 h-4 w-4" />,+ desc: <ArrowDown className="ml-2 h-4 w-4" />,+ }[column.getIsSorted() as string] ?? (+ <ArrowUpDown className="ml-2 h-4 w-4" />+ )}+ </Button>+ ),+ cell: ({ row }) => row.getValue("role") || "user",+ },+ {+ accessorKey: "createdAt",+ header: ({ column }) => (+ <Button+ variant="ghost"+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}+ className="p-0 hover:bg-transparent"+ >+ Created At+ {{+ asc: <ArrowUp className="ml-2 h-4 w-4" />,+ desc: <ArrowDown className="ml-2 h-4 w-4" />,+ }[column.getIsSorted() as string] ?? (+ <ArrowUpDown className="ml-2 h-4 w-4" />+ )}+ </Button>+ ),+ cell: ({ row }) =>+ new Date(row.getValue("createdAt")).toLocaleDateString(),+ },+ {+ id: "actions",+ header: "Actions",+ cell: ({ row }) => (+ <Button+ onClick={() => onImpersonate(row.original.id)}+ size="sm"+ variant="outline"+ className="flex items-center gap-1"+ disabled={row.original.id === userStore.getState().user?.id}+ >+ <User className="h-4 w-4" />+ Impersonate+ </Button>+ ),+ },+ ],+ [onImpersonate]+ );++ // Initialize the table+ const table = useReactTable({+ data: data?.users || [],+ columns,+ state: {+ sorting,+ columnFilters,+ pagination,+ globalFilter,+ },+ pageCount: data ? Math.ceil(data.total / pagination.pageSize) : -1,+ onSortingChange: (updater) =>+ setSorting(typeof updater === "function" ? updater(sorting) : updater),+ onColumnFiltersChange: (updater) =>+ setColumnFilters(+ typeof updater === "function" ? updater(columnFilters) : updater+ ),+ onPaginationChange: (updater) =>+ setPagination(+ typeof updater === "function" ? updater(pagination) : updater+ ),+ onGlobalFilterChange: setGlobalFilter,+ getCoreRowModel: getCoreRowModel(),+ getSortedRowModel: getSortedRowModel(),+ getFilteredRowModel: getFilteredRowModel(),+ getPaginationRowModel: getPaginationRowModel(),+ manualPagination: true,+ manualSorting: true,+ manualFiltering: true,+ });++ return (+ <div className="rounded-md border border-neutral-700">+ <Table>+ <TableHeader>+ {table.getHeaderGroups().map((headerGroup) => (+ <TableRow key={headerGroup.id}>+ {headerGroup.headers.map((header) => (+ <TableHead key={header.id}>+ {header.isPlaceholder+ ? null+ : flexRender(+ header.column.columnDef.header,+ header.getContext()+ )}+ </TableHead>+ ))}+ </TableRow>+ ))}+ </TableHeader>+ <TableBody>+ {isLoading ? (+ <UserTableSkeleton rowCount={pagination.pageSize} />+ ) : table.getRowModel().rows.length === 0 ? (+ <TableRow>+ <TableCell colSpan={columns.length} className="text-center py-4">+ No users found+ </TableCell>+ </TableRow>+ ) : (+ table.getRowModel().rows.map((row) => (+ <TableRow key={row.id}>+ {row.getVisibleCells().map((cell) => (+ <TableCell key={cell.id}>+ {flexRender(cell.column.columnDef.cell, cell.getContext())}+ </TableCell>+ ))}+ </TableRow>+ ))+ )}+ </TableBody>+ </Table>+ </div>+ );+}diff --git a/client/src/hooks/useAdminUsers.ts b/client/src/hooks/useAdminUsers.tsnew file mode 100644index 000000000..895549de8--- /dev/null+++ b/client/src/hooks/useAdminUsers.ts@@ -0,0 +1,136 @@+"use client";++import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { authClient } from "@/lib/auth";+import { ColumnFiltersState, SortingState } from "@tanstack/react-table";+import { AdminUser } from "@/types/admin";++export function useAdminUsers() {+ // Table state+ const [sorting, setSorting] = useState<SortingState>([+ { id: "createdAt", desc: true },+ ]);+ const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);+ const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 50 });+ const [globalFilter, setGlobalFilter] = useState("");++ // Function to fetch users+ const fetchUsers = async () => {+ // Default sort configuration from sorting state+ const sortBy = sorting.length > 0 ? sorting[0].id : "createdAt";+ const sortDirection =+ sorting.length > 0 ? (sorting[0].desc ? "desc" : "asc") : "desc";++ // Apply filters if any+ let emailFilter = "";+ let roleFilter = "";++ columnFilters.forEach((filter) => {+ if (filter.id === "email" && typeof filter.value === "string") {+ emailFilter = filter.value;+ }+ if (filter.id === "role" && typeof filter.value === "string") {+ roleFilter = filter.value;+ }+ });++ const response = await authClient.admin.listUsers({+ query: {+ limit: pagination.pageSize,+ offset: pagination.pageIndex * pagination.pageSize,+ sortBy,+ sortDirection,+ ...(emailFilter && {+ searchField: "email",+ searchOperator: "contains",+ searchValue: emailFilter.toLowerCase(),+ }),+ ...(roleFilter && {+ filterField: "role",+ filterOperator: "eq",+ filterValue: roleFilter,+ }),+ },+ });++ // Safely extract data+ const users = response.data?.users || [];+ const total = response.data?.total || 0;++ return {+ users,+ total,+ };+ };++ // Fetch data with React Query+ const { data, isLoading, isError, refetch } = useQuery<{+ users: AdminUser[];+ total: number;+ }>({+ queryKey: [+ "admin-users",+ pagination.pageIndex,+ pagination.pageSize,+ sorting,+ columnFilters,+ globalFilter,+ ],+ queryFn: fetchUsers,+ });++ // Handle impersonation+ const handleImpersonate = async (userId: string) => {+ try {+ await authClient.admin.impersonateUser({+ userId,+ });+ // Redirect to home after impersonation+ return true;+ } catch (err) {+ const errorMessage =+ err instanceof Error ? err.message : "Unknown error occurred";+ console.error(`Failed to impersonate user: ${errorMessage}`);+ return false;+ }+ };++ // Handle stop impersonation+ const handleStopImpersonating = async () => {+ try {+ await authClient.admin.stopImpersonating();+ return true;+ } catch (err) {+ const errorMessage =+ err instanceof Error ? err.message : "Unknown error occurred";+ console.error(`Failed to stop impersonation: ${errorMessage}`);+ return false;+ }+ };++ return {+ // Data+ users: data?.users || [],+ total: data?.total || 0,++ // Loading state+ isLoading,+ isError,++ // Table state+ sorting,+ setSorting,+ columnFilters,+ setColumnFilters,+ pagination,+ setPagination,+ globalFilter,+ setGlobalFilter,++ // Actions+ refetch,+ handleImpersonate,+ handleStopImpersonating,+ };+}diff --git a/client/src/hooks/useStopImpersonation.ts b/client/src/hooks/useStopImpersonation.tsnew file mode 100644index 000000000..b43395335--- /dev/null+++ b/client/src/hooks/useStopImpersonation.ts@@ -0,0 +1,27 @@+import { useEffect } from "react";+import { authClient } from "@/lib/auth";++// Add stopImpersonating to Window interface+declare global {+ interface Window {+ stopImpersonating: () => Promise<boolean>;+ }+}++export function useStopImpersonation() {+ useEffect(() => {+ if (typeof window !== "undefined") {+ window.stopImpersonating = async () => {+ try {+ await authClient.admin.stopImpersonating();+ console.log("Successfully stopped impersonating. Reloading page...");+ window.location.href = "/admin";+ return true;+ } catch (err) {+ console.error("Failed to stop impersonation:", err);+ return false;+ }+ };+ }+ }, []);+}diff --git a/client/src/middleware.ts b/client/src/middleware.tsindex 81c257585..55b996197 100644--- a/client/src/middleware.ts+++ b/client/src/middleware.ts@@ -33,10 +33,10 @@ export async function middleware(request: NextRequest) {const excludedRoutes = ["login","signup",- "settings","subscribe","invitation","auth",+ "admin","_next","api",];diff --git a/client/src/types/admin.ts b/client/src/types/admin.tsnew file mode 100644index 000000000..75b2bdff3--- /dev/null+++ b/client/src/types/admin.ts@@ -0,0 +1,16 @@+export type AdminUser = {+ id: string;+ name: string | null;+ email: string;+ role?: string;+ createdAt: string | Date;+};++export interface UsersResponse {+ data?: {+ users: AdminUser[];+ total: number;+ limit?: number;+ offset?: number;+ };+}