54 lines
1.6 KiB
PHP
54 lines
1.6 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;
|
|
use Illuminate\Support\Facades\Hash;
|
|
|
|
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);
|
|
}
|
|
print_r($request->all());
|
|
|
|
if ($this->apiToken === null) {
|
|
abort(401, 'Le token d\'authentification est incorrect');
|
|
}
|
|
$brand = Brand::whereHas('services', function (Builder $query) {
|
|
$query->where("bearer_token", Hash::make($this->apiToken));
|
|
})->first();
|
|
|
|
if (!$brand) {
|
|
abort(401, 'Le token d\'authentification est incorrect');
|
|
}
|
|
|
|
$serviceStat = ServiceStat::firstOrNew(['date' => date('Y-m-d')]);
|
|
$serviceStat->brand_id = $brand->id;
|
|
$serviceStat->service_id = Service::where('bearer_token', Hash::make($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);
|
|
}
|
|
}
|