Add user management
This commit is contained in:
44
src/actions/users/deleteUser.ts
Normal file
44
src/actions/users/deleteUser.ts
Normal 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" };
|
||||
}
|
||||
Reference in New Issue
Block a user