48 lines
1.4 KiB
PHP
48 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use App\Models\Brand;
|
|
use App\Models\Service;
|
|
use App\Models\ServiceStat;
|
|
use Closure;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Http\Request;
|
|
|
|
class CheckBrand
|
|
{
|
|
private $apiToken;
|
|
|
|
/**
|
|
* Handle an incoming request.
|
|
*
|
|
* @param \Illuminate\Http\Request $request
|
|
* @param \Closure $next
|
|
* @return mixed
|
|
*/
|
|
public function handle(Request $request, Closure $next)
|
|
{
|
|
if ($request->bearerToken() !== null)
|
|
$this->apiToken = $request->bearerToken();
|
|
else
|
|
$this->apiToken = ($request->api_token !== null ? $request->api_token : null);
|
|
|
|
if ($this->apiToken === null)
|
|
die("Le token d'authentification est incorrect");
|
|
$brand = Brand::whereHas('services', function (Builder $query) {
|
|
$query->where("api_token", hash('sha256', $this->apiToken));
|
|
})->first();
|
|
|
|
if (!$brand)
|
|
die("Le token d'authentification est incorrect");
|
|
|
|
$serviceStat = ServiceStat::firstOrNew(['date' => date('Y-m-d')]);
|
|
$serviceStat->brand_id = $brand->id;
|
|
$serviceStat->service_id = Service::where('api_token', hash('sha256', $this->apiToken))->first()->id;
|
|
$serviceStat->nb_calls = $serviceStat->nb_calls === 0 ? 1 : $serviceStat->nb_calls + 1;
|
|
$serviceStat->save();
|
|
|
|
$request->request->add(['brand_id' => $brand->id]);
|
|
return $next($request);
|
|
}
|
|
}
|