import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api"; import { requireAdminSession } from "@/lib/server/auth/current-user"; import { AccountStoreError, getPlatformUserById, updatePlatformUser } from "@/lib/server/account-store"; import { hasSuperAdminAccess } from "@/lib/auth/permissions"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; export async function POST(request: Request) { try { const session = await requireAdminSession(); const body = await readJsonBody>(request); const userId = requiredString(body.userId, "账号 ID"); const target = await getPlatformUserById(userId, { includeDisabled: true }); if (!target) throw new AccountStoreError("账号不存在。", 404); if (!hasSuperAdminAccess(session.user) && (session.user.role !== "organization_admin" || target.role !== "user" || target.organizationId !== session.user.organizationId)) { throw new AccountStoreError("组织管理员只能重置本组织普通用户密码。", 403); } const newPassword = requiredString(body.newPassword, "新密码"); if (newPassword.length < 8) throw new AccountStoreError("新密码至少需要 8 位。", 400); const user = await updatePlatformUser(userId, { password: newPassword, clearLoginLock: true }); return jsonOk({ ok: true, userId: user.id }); } catch (error) { return jsonError(error, 500, { request, source: "api.admin.accounts.password", logClientErrors: true }); } } function requiredString(value: unknown, label: string): string { if (typeof value === "string" && value.trim()) return value.trim(); throw new AccountStoreError(`${label}不能为空。`, 400); }