Files
v2.admin.gaertan.art/src/actions/users/getUsers.ts
2026-02-03 13:12:31 +01:00

44 lines
1.1 KiB
TypeScript

"use server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import type { SessionWithRole } from "@/types/auth";
import type { UserRole, UsersListRow } from "@/types/users";
import { headers } from "next/headers";
// Returns all users for the admin users table.
export async function getUsers(): Promise<UsersListRow[]> {
const session = await auth.api.getSession({ headers: await headers() });
const role = (session as SessionWithRole)?.user?.role;
if (!session || role !== "admin") {
throw new Error("Forbidden");
}
const rows = await prisma.user.findMany({
orderBy: { createdAt: "asc" },
select: {
id: true,
name: true,
email: true,
role: true,
emailVerified: true,
createdAt: true,
updatedAt: true,
},
});
return rows.map((r) => {
if (r.role !== "admin" && r.role !== "user") {
throw new Error(`Unexpected user role: ${r.role}`);
}
return {
...r,
role: r.role as UserRole,
createdAt: r.createdAt.toISOString(),
updatedAt: r.updatedAt.toISOString(),
};
});
}