#feature: add ip operation log & sql generator
This commit is contained in:
24
app/Http/Controllers/Admin/AdminMetaController.php
Normal file
24
app/Http/Controllers/Admin/AdminMetaController.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Support\IpAccess;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class AdminMetaController extends Controller
|
||||
{
|
||||
public function show(Request $request): JsonResponse
|
||||
{
|
||||
$ipAddress = $request->ip();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'is_admin' => IpAccess::isAdmin($ipAddress),
|
||||
'ip' => $ipAddress,
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
92
app/Http/Controllers/Admin/IpUserMappingController.php
Normal file
92
app/Http/Controllers/Admin/IpUserMappingController.php
Normal file
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\IpUserMapping;
|
||||
use App\Models\OperationLog;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class IpUserMappingController extends Controller
|
||||
{
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$mappings = IpUserMapping::query()
|
||||
->orderBy('ip_address')
|
||||
->get();
|
||||
|
||||
$unmappedIps = OperationLog::query()
|
||||
->select(
|
||||
'operation_logs.ip_address',
|
||||
DB::raw('COUNT(*) as logs_count'),
|
||||
DB::raw('MAX(operation_logs.created_at) as last_seen_at')
|
||||
)
|
||||
->leftJoin('ip_user_mappings', 'operation_logs.ip_address', '=', 'ip_user_mappings.ip_address')
|
||||
->whereNull('ip_user_mappings.id')
|
||||
->where('operation_logs.ip_address', '!=', '')
|
||||
->groupBy('operation_logs.ip_address')
|
||||
->orderByDesc('last_seen_at')
|
||||
->get();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'mappings' => $mappings,
|
||||
'unmapped_ips' => $unmappedIps,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'ip_address' => ['required', 'ip', 'max:64', 'unique:ip_user_mappings,ip_address'],
|
||||
'user_name' => ['required', 'string', 'max:128'],
|
||||
'remark' => ['nullable', 'string', 'max:255'],
|
||||
]);
|
||||
|
||||
$mapping = IpUserMapping::query()->create($data);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'mapping' => $mapping,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request, IpUserMapping $mapping): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'ip_address' => [
|
||||
'required',
|
||||
'ip',
|
||||
'max:64',
|
||||
Rule::unique('ip_user_mappings', 'ip_address')->ignore($mapping->id),
|
||||
],
|
||||
'user_name' => ['required', 'string', 'max:128'],
|
||||
'remark' => ['nullable', 'string', 'max:255'],
|
||||
]);
|
||||
|
||||
$mapping->update($data);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'mapping' => $mapping->refresh(),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy(IpUserMapping $mapping): JsonResponse
|
||||
{
|
||||
$mapping->delete();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
]);
|
||||
}
|
||||
}
|
||||
67
app/Http/Controllers/Admin/OperationLogController.php
Normal file
67
app/Http/Controllers/Admin/OperationLogController.php
Normal file
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\OperationLog;
|
||||
use App\Support\IpAccess;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class OperationLogController extends Controller
|
||||
{
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:200'],
|
||||
'q' => ['nullable', 'string', 'max:255'],
|
||||
'method' => ['nullable', 'string', 'max:10'],
|
||||
]);
|
||||
|
||||
$query = OperationLog::query()->orderByDesc('id');
|
||||
$isAdmin = IpAccess::isAdmin($request->ip());
|
||||
|
||||
$search = trim((string) ($data['q'] ?? ''));
|
||||
if ($search !== '') {
|
||||
$query->where(function ($builder) use ($search, $isAdmin): void {
|
||||
$builder->where('ip_address', 'like', "%{$search}%")
|
||||
->orWhere('path', 'like', "%{$search}%")
|
||||
->orWhere('route_name', 'like', "%{$search}%");
|
||||
|
||||
if ($isAdmin) {
|
||||
$builder->orWhere('user_label', 'like', "%{$search}%");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$method = strtoupper((string) ($data['method'] ?? ''));
|
||||
if ($method !== '') {
|
||||
$query->where('method', $method);
|
||||
}
|
||||
|
||||
$perPage = (int) ($data['per_page'] ?? 50);
|
||||
$logs = $query->paginate($perPage);
|
||||
$items = collect($logs->items())->map(function (OperationLog $log) use ($isAdmin): array {
|
||||
$payload = $log->toArray();
|
||||
if (!$isAdmin) {
|
||||
$payload['user_label'] = null;
|
||||
}
|
||||
|
||||
return $payload;
|
||||
})->all();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'logs' => $items,
|
||||
'pagination' => [
|
||||
'current_page' => $logs->currentPage(),
|
||||
'last_page' => $logs->lastPage(),
|
||||
'per_page' => $logs->perPage(),
|
||||
'total' => $logs->total(),
|
||||
],
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
66
app/Http/Controllers/SqlGeneratorController.php
Normal file
66
app/Http/Controllers/SqlGeneratorController.php
Normal file
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class SqlGeneratorController extends Controller
|
||||
{
|
||||
/**
|
||||
* 查询 agentslave.case_extras 中已存在的 OB 外部 ID 记录。
|
||||
*/
|
||||
public function checkObExternalId(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$request->validate([
|
||||
'case_codes' => 'required|array|min:1',
|
||||
'case_codes.*' => 'required|string|max:255',
|
||||
]);
|
||||
|
||||
$caseCodes = array_values(array_unique(array_filter(array_map('trim', $request->input('case_codes')))));
|
||||
|
||||
if (empty($caseCodes)) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => '请提供有效的 case_id 列表'
|
||||
], 400);
|
||||
}
|
||||
|
||||
$existingCaseCodes = [];
|
||||
foreach (array_chunk($caseCodes, 1000) as $chunk) {
|
||||
$results = DB::connection('agentslave')
|
||||
->table('case_extras')
|
||||
->where('source', 'ob')
|
||||
->where('field', 'OB Case ID')
|
||||
->whereIn('case_code', $chunk)
|
||||
->pluck('case_code')
|
||||
->all();
|
||||
|
||||
$existingCaseCodes = array_merge($existingCaseCodes, $results);
|
||||
}
|
||||
|
||||
$existingCaseCodes = array_values(array_unique(array_map('strval', $existingCaseCodes)));
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'existing_case_codes' => $existingCaseCodes,
|
||||
],
|
||||
]);
|
||||
} catch (ValidationException $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => '请求参数验证失败',
|
||||
'errors' => $e->errors(),
|
||||
], 422);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => '查询 case_extras 失败: ' . $e->getMessage(),
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
30
app/Http/Middleware/AdminIpMiddleware.php
Normal file
30
app/Http/Middleware/AdminIpMiddleware.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Support\IpAccess;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class AdminIpMiddleware
|
||||
{
|
||||
/**
|
||||
* @param Closure(Request): Response $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if (!IpAccess::isAdmin($request->ip())) {
|
||||
if ($request->expectsJson() || $request->is('api/*')) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => '无权限访问',
|
||||
], 403);
|
||||
}
|
||||
|
||||
abort(403);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
129
app/Http/Middleware/OperationLogMiddleware.php
Normal file
129
app/Http/Middleware/OperationLogMiddleware.php
Normal file
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Models\IpUserMapping;
|
||||
use App\Models\OperationLog;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Throwable;
|
||||
|
||||
class OperationLogMiddleware
|
||||
{
|
||||
/**
|
||||
* @param Closure(Request): Response $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$startAt = microtime(true);
|
||||
|
||||
try {
|
||||
$response = $next($request);
|
||||
} catch (Throwable $exception) {
|
||||
$this->recordLog($request, null, $startAt, 500);
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$this->recordLog($request, $response, $startAt, $response->getStatusCode());
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function shouldLog(Request $request): bool
|
||||
{
|
||||
$methods = config('toolbox.operation_log.methods', []);
|
||||
if (!in_array($request->method(), $methods, true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $request->is('api/*');
|
||||
}
|
||||
|
||||
private function recordLog(Request $request, ?Response $response, float $startAt, int $statusCode): void
|
||||
{
|
||||
if (!$this->shouldLog($request)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$ipAddress = $request->ip() ?? '';
|
||||
$mapping = $ipAddress !== ''
|
||||
? IpUserMapping::query()->where('ip_address', $ipAddress)->first()
|
||||
: null;
|
||||
|
||||
OperationLog::query()->create([
|
||||
'ip_address' => $ipAddress,
|
||||
'user_label' => $mapping?->user_name,
|
||||
'method' => $request->method(),
|
||||
'path' => '/' . ltrim($request->path(), '/'),
|
||||
'route_name' => $request->route()?->getName(),
|
||||
'status_code' => $statusCode,
|
||||
'duration_ms' => (int) round((microtime(true) - $startAt) * 1000),
|
||||
'request_payload' => $this->buildPayload($request),
|
||||
'user_agent' => substr((string) $request->userAgent(), 0, 255),
|
||||
]);
|
||||
} catch (Throwable $exception) {
|
||||
Log::warning('Failed to record operation log.', [
|
||||
'error' => $exception->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function buildPayload(Request $request): array
|
||||
{
|
||||
$payload = $request->all();
|
||||
if (empty($payload)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$redactKeys = array_map('strtolower', config('toolbox.operation_log.redact_keys', []));
|
||||
$payload = $this->redactPayload($payload, $redactKeys);
|
||||
|
||||
$encoded = json_encode($payload, JSON_UNESCAPED_UNICODE);
|
||||
if ($encoded === false) {
|
||||
return ['_unserializable' => true];
|
||||
}
|
||||
|
||||
$maxLength = (int) config('toolbox.operation_log.max_payload_length', 2000);
|
||||
if (strlen($encoded) <= $maxLength) {
|
||||
return $payload;
|
||||
}
|
||||
|
||||
return [
|
||||
'_truncated' => true,
|
||||
'preview' => substr($encoded, 0, $maxLength),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
* @param array<int, string> $redactKeys
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function redactPayload(array $payload, array $redactKeys): array
|
||||
{
|
||||
$redacted = [];
|
||||
|
||||
foreach ($payload as $key => $value) {
|
||||
$lowerKey = strtolower((string) $key);
|
||||
if (in_array($lowerKey, $redactKeys, true)) {
|
||||
$redacted[$key] = '[redacted]';
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_array($value)) {
|
||||
$redacted[$key] = $this->redactPayload($value, $redactKeys);
|
||||
continue;
|
||||
}
|
||||
|
||||
$redacted[$key] = $value;
|
||||
}
|
||||
|
||||
return $redacted;
|
||||
}
|
||||
}
|
||||
17
app/Models/IpUserMapping.php
Normal file
17
app/Models/IpUserMapping.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class IpUserMapping extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'ip_address',
|
||||
'user_name',
|
||||
'remark',
|
||||
];
|
||||
}
|
||||
27
app/Models/OperationLog.php
Normal file
27
app/Models/OperationLog.php
Normal file
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class OperationLog extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'ip_address',
|
||||
'user_label',
|
||||
'method',
|
||||
'path',
|
||||
'route_name',
|
||||
'status_code',
|
||||
'duration_ms',
|
||||
'request_payload',
|
||||
'user_agent',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'request_payload' => 'array',
|
||||
];
|
||||
}
|
||||
50
app/Support/IpAccess.php
Normal file
50
app/Support/IpAccess.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
class IpAccess
|
||||
{
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function adminIps(): array
|
||||
{
|
||||
return config('toolbox.admin_ips', []);
|
||||
}
|
||||
|
||||
public static function isAdmin(?string $ip): bool
|
||||
{
|
||||
if (!is_string($ip) || $ip === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$adminIps = self::adminIps();
|
||||
if (empty($adminIps)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($adminIps as $pattern) {
|
||||
if ($pattern === $ip) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (str_contains($pattern, '*') && self::matchWildcard($pattern, $ip)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function matchWildcard(string $pattern, string $ip): bool
|
||||
{
|
||||
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$escaped = preg_quote($pattern, '#');
|
||||
$regex = str_replace('\*', '[0-9.]*', $escaped);
|
||||
|
||||
return (bool) preg_match('#^' . $regex . '$#', $ip);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user