Viewing file: LogApiRequests_wofb.php (2.85 KB) -rw-r--r-- Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
<?php
namespace App\Http\Middleware;
use GuzzleHttp\Client;
use App\Models\Request;
use Closure;
use Illuminate\Http\Request as HttpRequest;
use Illuminate\Support\Facades\Auth;
class LogApiRequests
{
public function handle(HttpRequest $request, Closure $next)
{
$start = microtime(true);
$response = $next($request);
$end = microtime(true);
$responseTime = round(($end - $start) * 1000, 2);
$ipAddress = $request->ip();
// Make a request to the IP geolocation service
$client = new Client();
$resp = $client->get("http://ip-api.com/json/{$ipAddress}");
// Retrieve the response body
$body = $resp->getBody();
// Parse the JSON response
$location = json_decode($body);
// if (Auth::user()->last_country==$location->country) {
// //same
// }else {
// //not same
// }
$token="xaat-af523ddf-b600-46aa-a804-cab5d82bcadd";
$client = new Client();
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
// 'X-Foo' => ['Bar', 'Baz'],
'X-Axiom-Org-ID' => "jiff-7ijc",
];
// if ($response->getStatusCode()!==200 || isset($response->original['error'])) {
if ($response->getStatusCode() ==200 || $request->method()=="get") {
$res_content="{}";
}else {
$res_content=$response->getContent();
}
$res = $client->request('POST', 'https://api.axiom.co/v1/datasets/api_logs/ingest', [
'headers' => $headers,
'json' => [
[
'duration_ms' => $responseTime,
'ip_address' => $ipAddress,
'location' =>$location,
'url' => $request->url(),
'path' => $request->path(),
'http_method' => $request->method(),
'request_parameters' => json_encode($request->all()),
'response_code' => $response->getStatusCode() == 402 ? 400 : $response->getStatusCode(),
'response_body' => $res_content
]
]
]);
if ($response->getStatusCode()==200) {
return $response;
}else if ($response->getStatusCode()==500){
return response()->json(['error' => 'true', 'message' =>"Something is Wrong, Please Try Again"],500);
}else if ($response->getStatusCode()==402) {
return response()->json(['error' => 'true', 'message' =>"Bad Request"],400);
}else{
return response()->json( $res_content,$response->getStatusCode());
}
}
}
?>
|