ldc-crm/app/Http/Middleware/Authenticate.php
2021-08-02 11:46:08 +02:00

99 lines
3.2 KiB
PHP

<?php
namespace App\Http\Middleware;
use App\Lib\Helper;
use App\Models\Service;
use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Route;
/**
* Updated for ApiV2
*/
class Authenticate extends Middleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string[] ...$guards
* @return mixed
*
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$guards)
{
$isApiV1Request = $request->isJson() && Helper::isRequestForApiV1($request);
$isApiV2Request = $request->isJson() && Helper::isRequestForApiV2($request);
if ($isApiV2Request) {
// https://stackoverflow.com/questions/25838183/what-is-the-oauth-2-0-bearer-token-exactly/25843058
/**
* Un token devrais être fourni pour chaque requete apres authentification
* api_token param est requis par Auth
*/
$apiToken = $request->api_token;
if (is_null($apiToken)) {
$this->unauthenticated($request, $guards);
}
/**
** All ApiV2 routes must pass Brand model to controller action since a Brand owns
** a service token, otherwise the api cannot be called.
** This hack is a custom binder instead of passing
** this to route as a parameter
*/
if (!($route = Helper::getRoute($request))) {
$this->unauthenticated($request, $guards);
}
try {
$service = Service::getFromApiToken($apiToken);
$service->authenticateApi($guards, $apiToken);
app()->bind(Service::class, function () use ($service) {
return $service;
});
} catch (ModelNotFoundException $e) {
throw new AuthenticationException('Unauthenticated.', $guards);
}
}
// TODO: check this works
if ($isApiV1Request) {
// Use patched v1 Auth mecanism (without bearer reimplementation)
$bearerToken = $request->bearerToken();
$brand = Service::getFromBearerToken($bearerToken)->brand;
$request->request->add(['brand_id' => $brand->id]);
$response = $next($request);
} else {
// Use Laravel auth check mecanism
$response = \call_user_func_array(
[$this, 'parent::' . __FUNCTION__],
array_merge([$request, $next], $guards)
);
}
if ($isApiV2Request || $isApiV1Request) {
Service::incrementStat($apiToken);
}
return $response;
}
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}