91 lines
3.0 KiB
TypeScript
91 lines
3.0 KiB
TypeScript
"use server";
|
|
|
|
import { eq } from "drizzle-orm";
|
|
import { headers } from "next/headers";
|
|
import { revalidatePath } from "next/cache";
|
|
import { z } from "zod";
|
|
|
|
import { getDb } from "@/db";
|
|
import { users } from "@/db/schema";
|
|
import { getAuth, requireAdmin } from "@/lib/auth/server";
|
|
import { securityLog } from "@/lib/security/http";
|
|
|
|
export interface CreateAccountState {
|
|
status: "idle" | "error" | "success";
|
|
message: string;
|
|
}
|
|
|
|
const accountSchema = z
|
|
.object({
|
|
name: z.string().trim().min(1).max(100),
|
|
email: z.email().transform((value) => value.toLowerCase()),
|
|
password: z.string().min(12).max(128),
|
|
passwordConfirmation: z.string(),
|
|
})
|
|
.refine((data) => data.password === data.passwordConfirmation, {
|
|
path: ["passwordConfirmation"],
|
|
});
|
|
|
|
export async function createAccount(
|
|
_previousState: CreateAccountState,
|
|
formData: FormData,
|
|
): Promise<CreateAccountState> {
|
|
const admin = await requireAdmin();
|
|
const parsed = accountSchema.safeParse(Object.fromEntries(formData));
|
|
if (!parsed.success) {
|
|
return { status: "error", message: "โปรดตรวจสอบชื่อ อีเมล และรหัสผ่านให้ถูกต้อง" };
|
|
}
|
|
|
|
const existing = await getDb().query.users.findFirst({
|
|
columns: { id: true },
|
|
where: eq(users.email, parsed.data.email),
|
|
});
|
|
if (existing) {
|
|
return { status: "error", message: "อีเมลนี้มีบัญชีอยู่แล้ว" };
|
|
}
|
|
|
|
try {
|
|
await getAuth().api.createUser({
|
|
body: {
|
|
name: parsed.data.name,
|
|
email: parsed.data.email,
|
|
password: parsed.data.password,
|
|
role: "admin",
|
|
data: { emailVerified: true },
|
|
},
|
|
headers: await headers(),
|
|
});
|
|
} catch {
|
|
return { status: "error", message: "สร้างบัญชีไม่สำเร็จ โปรดลองอีกครั้ง" };
|
|
}
|
|
|
|
revalidatePath("/admin/register");
|
|
securityLog("account-created", { actorId: admin.user.id });
|
|
return { status: "success", message: `สร้างบัญชี ${parsed.data.email} แล้ว` };
|
|
}
|
|
|
|
export async function removeAccount(
|
|
userId: string,
|
|
): Promise<{ status: "error" | "success"; message?: string }> {
|
|
const session = await requireAdmin();
|
|
if (!z.string().min(1).max(128).safeParse(userId).success) {
|
|
return { status: "error", message: "บัญชีไม่ถูกต้อง" };
|
|
}
|
|
if (userId === session.user.id) {
|
|
return { status: "error", message: "ไม่สามารถลบบัญชีที่กำลังใช้งานอยู่" };
|
|
}
|
|
|
|
try {
|
|
await getAuth().api.removeUser({
|
|
body: { userId },
|
|
headers: await headers(),
|
|
});
|
|
} catch {
|
|
return { status: "error", message: "ลบบัญชีไม่สำเร็จ โปรดลองอีกครั้ง" };
|
|
}
|
|
|
|
revalidatePath("/admin/register");
|
|
securityLog("account-removed", { actorId: session.user.id, targetId: userId });
|
|
return { status: "success" };
|
|
}
|