'system']); $username = trim($_POST['username'] ?? ''); $password = (string)($_POST['password'] ?? ''); $realName = trim($_POST['real_name'] ?? ''); $roleId = (int)($_POST['role_id'] ?? 0); $isActive = isset($_POST['is_active']) ? ((int)$_POST['is_active'] ? 1 : 0) : 1; if ($username === '' || !preg_match('/^[a-zA-Z0-9_]{3,50}$/', $username)) { Response::error('账号需为3-50位字母/数字/下划线', 400); } if (strlen($password) < 8 || !preg_match('/[a-zA-Z]/', $password) || !preg_match('/\d/', $password)) { Response::error('密码需不少于8位,且同时包含字母和数字', 400); } if ($roleId <= 0) { Response::error('请选择角色', 400); } $chk = $pdo->prepare("SELECT COUNT(*) FROM system_users WHERE username = ?"); $chk->execute([$username]); if ((int)$chk->fetchColumn() > 0) { Response::error('账号已存在'); } $chkRole = $pdo->prepare("SELECT COUNT(*) FROM system_roles WHERE id = ?"); $chkRole->execute([$roleId]); if ((int)$chkRole->fetchColumn() === 0) { Response::error('角色不存在', 400); } $stmt = $pdo->prepare( "INSERT INTO system_users (username, password, real_name, role_id, is_active) VALUES (?, ?, ?, ?, ?)" ); $stmt->execute([$username, password_hash($password, PASSWORD_DEFAULT), $realName !== '' ? $realName : null, $roleId, $isActive]); $newId = (int)$pdo->lastInsertId(); logCurrent('add', 'system', 'system_users', $newId, ['username' => $username, 'role_id' => $roleId, 'is_active' => $isActive]); Response::success(['id' => $newId], '新增成功');