Files
toolbox/app/Http/Controllers/Admin/IpUserMappingController.php
T

109 lines
3.4 KiB
PHP

<?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);
$syncedCount = $this->syncMissingOperationLogUserLabels($mapping->ip_address, $mapping->user_name);
return response()->json([
'success' => true,
'data' => [
'mapping' => $mapping,
'synced_operation_logs_count' => $syncedCount,
],
]);
}
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);
$mapping->refresh();
$syncedCount = $this->syncMissingOperationLogUserLabels($mapping->ip_address, $mapping->user_name);
return response()->json([
'success' => true,
'data' => [
'mapping' => $mapping,
'synced_operation_logs_count' => $syncedCount,
],
]);
}
public function destroy(IpUserMapping $mapping): JsonResponse
{
$mapping->delete();
return response()->json([
'success' => true,
]);
}
private function syncMissingOperationLogUserLabels(string $ipAddress, string $userName): int
{
return DB::table('operation_logs')
->where('ip_address', $ipAddress)
->where(function ($query): void {
$query->whereNull('user_label')
->orWhere('user_label', '');
})
->update(['user_label' => $userName]);
}
}