Add user management

This commit is contained in:
2026-01-01 18:34:02 +01:00
parent 2fcf19c0df
commit 36fb2358dd
26 changed files with 1047 additions and 56 deletions

View File

@ -0,0 +1,44 @@
"use server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { headers } from "next/headers";
import { z } from "zod/v4";
export async function deleteUser(id: string) {
const userId = z.string().min(1).parse(id);
const session = await auth.api.getSession({ headers: await headers() });
const role = (session as any)?.user?.role as string | undefined;
const currentUserId = (session as any)?.user?.id as string | undefined;
if (!session || role !== "admin") throw new Error("Forbidden");
if (!currentUserId) throw new Error("Session missing user id");
if (userId === currentUserId) {
throw new Error("You cannot delete your own account.");
}
const target = await await_attachTarget(userId);
// Prevent deleting last admin
if (target.role === "admin") {
const adminCount = await prisma.user.count({ where: { role: "admin" } });
if (adminCount <= 1) {
throw new Error("Cannot delete the last admin user.");
}
}
await prisma.user.delete({ where: { id: userId } });
return { ok: true };
}
async function await_attachTarget(userId: string) {
const target = await prisma.user.findUnique({
where: { id: userId },
select: { id: true, role: true },
});
if (!target) throw new Error("User not found.");
return target as { id: string; role: "admin" | "user" };
}