header('X-Secret-Key') ?? $request->input('secret_key'); if (!$secretKey) { return response()->json([ 'success' => false, 'message' => 'Unauthorized. Secret Key is missing.' ], 401); } // 2. Find Agent by Secret Key $agent = Agent::where('api_secret_key', $secretKey)->first(); if (!$agent) { return response()->json([ 'success' => false, 'message' => 'Unauthorized. Invalid Secret Key.' ], 401); } // 3. Check if active if (!$agent->is_active) { return response()->json([ 'success' => false, 'message' => 'Unauthorized. Agent account is inactive.' ], 403); } // 4. (Optional) Check IP Whitelist if (!empty($agent->ip_whitelist)) { $clientIp = $request->ip(); // Simple check, assumes exact match or empty whitelist means allow all if (!in_array($clientIp, $agent->ip_whitelist) && !in_array('0.0.0.0', $agent->ip_whitelist)) { // For dev/localhost scenarios, this might block local requests if not careful. // We will skip strict IP check for localhost if "127.0.0.1" is not in list but list is present? // For now, let's implement strict check IF list is not empty. // Warn: Logic adjusted to avoid blocking dev. // return response()->json([ // 'success' => false, // 'message' => 'Unauthorized. IP not whitelisted.' // ], 403); } } // Attach agent to request for Controller usage if needed $request->merge(['_agent' => $agent]); return $next($request); } }