feat(admin): add safe account reset
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { isPostgresError, queryAdminRows } from "@/lib/admin/database";
|
||||
import {
|
||||
adminErrorResponse,
|
||||
invalidQueryResponse,
|
||||
requestId,
|
||||
requireHighRiskAdminMutation,
|
||||
} from "@/lib/admin/http";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
const resetSchema = z.object({
|
||||
userId: z.string().uuid(),
|
||||
confirmation: z.literal("RESET"),
|
||||
reason: z.string().trim().min(1).max(500),
|
||||
});
|
||||
|
||||
type ResetRow = {
|
||||
user_id: string;
|
||||
email: string;
|
||||
credits: number;
|
||||
chat_sessions_deleted: number;
|
||||
chart_profiles_deleted: number;
|
||||
synastry_reports_deleted: number;
|
||||
};
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await requireHighRiskAdminMutation(
|
||||
request,
|
||||
"admin.users.manage_roles",
|
||||
);
|
||||
const parsed = resetSchema.safeParse(await request.json().catch(() => null));
|
||||
if (!parsed.success) return invalidQueryResponse(parsed.error.flatten());
|
||||
|
||||
const rows = await queryAdminRows<ResetRow>(
|
||||
"select * from public.admin_reset_customer_account($1, $2, $3, $4)",
|
||||
[
|
||||
session.user.id,
|
||||
parsed.data.userId,
|
||||
parsed.data.reason,
|
||||
requestId(request),
|
||||
],
|
||||
);
|
||||
const row = rows[0];
|
||||
if (!row) return NextResponse.json({ error: "用户不存在" }, { status: 404 });
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
userId: row.user_id,
|
||||
email: row.email,
|
||||
credits: row.credits,
|
||||
deleted: {
|
||||
chatSessions: row.chat_sessions_deleted,
|
||||
chartProfiles: row.chart_profiles_deleted,
|
||||
synastryReports: row.synastry_reports_deleted,
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (
|
||||
isPostgresError(error)
|
||||
&& error.code === "P0002"
|
||||
&& error instanceof Error
|
||||
&& error.message.includes("admin_customer_not_found_or_identity_bridge_mismatch")
|
||||
) {
|
||||
return NextResponse.json({ error: "用户不存在或账号数据不完整" }, { status: 404 });
|
||||
}
|
||||
return adminErrorResponse(error);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user