Api calls ok
This commit is contained in:
parent
50d304c6ce
commit
c0c1608ad5
26 changed files with 691 additions and 143 deletions
44
app/Enums/Api/ApiError.php
Normal file
44
app/Enums/Api/ApiError.php
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
namespace App\Enums\Api;
|
||||
|
||||
use App\Traits\Enums\BaseEnum;
|
||||
|
||||
enum ApiError: int
|
||||
{
|
||||
use BaseEnum;
|
||||
|
||||
case modelNotFound = 101;
|
||||
case validationFailed = 102;
|
||||
case customerExists = 103;
|
||||
case customerAlreadyActive = 110;
|
||||
case customerNotActivated = 116;
|
||||
case authFailed = 117;
|
||||
case apiAuthFailed = 119;
|
||||
case singleOptinCustomerExists = 120;
|
||||
case methodNotAllowed = 150;
|
||||
case wrongTimeStamp = 151;
|
||||
case missingParameter = 400;
|
||||
case authorizationException = 403;
|
||||
case throttleRequestsException = 429;
|
||||
|
||||
/**
|
||||
* Optionnal labels definition
|
||||
*/
|
||||
private const LABELS = [
|
||||
self::modelNotFound->name => '%s introuvable.',
|
||||
self::validationFailed->name => 'Impossible de valider les données',
|
||||
self::customerExists->name => 'L\'utilisateur est déjà enregistré sur ce site',
|
||||
self::customerNotActivated->name => 'Le compte n\'est pas activé',
|
||||
self::customerAlreadyActive->name => 'Le compte est déjà activé',
|
||||
self::singleOptinCustomerExists->name => 'Le single optin ne peut être ajouté car un compte existe.',
|
||||
self::authFailed->name => 'Echec de l\'authentification du compte',
|
||||
self::apiAuthFailed->name => 'Echec de l\'authentification client à l\'Api LDC-CRM pour ce service',
|
||||
self::methodNotAllowed->name => 'This method is not allowed for this request',
|
||||
self::wrongTimeStamp->name => 'Your request is malformed, please check timestamp header and
|
||||
parameter',
|
||||
self::missingParameter->name => 'The request is missing some parameters',
|
||||
self::authorizationException->name => 'You are not autorized to access this',
|
||||
self::throttleRequestsException->name => 'Throttle: too many request have been attempted, please retry later'
|
||||
];
|
||||
}
|
||||
13
app/Enums/Api/ApiStatus.php
Normal file
13
app/Enums/Api/ApiStatus.php
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<?php
|
||||
|
||||
namespace App\Enums\Api;
|
||||
|
||||
use App\Traits\Enums\BaseEnum;
|
||||
|
||||
enum ApiStatus: int
|
||||
{
|
||||
use BaseEnum;
|
||||
|
||||
case OK = 1;
|
||||
case KO = 2;
|
||||
}
|
||||
|
|
@ -1,84 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Kwaadpepper\Enum\BaseEnumRoutable;
|
||||
|
||||
/**
|
||||
* This describes an API error.
|
||||
*
|
||||
* @method static self modelNotFound()
|
||||
* The request model was not found (typically the customer)
|
||||
*
|
||||
* @method static self validationFailed()
|
||||
* This means some data could not be validated,
|
||||
* you may have to look into message to get the details
|
||||
*
|
||||
* @method static self apiAuthFailed()
|
||||
* The authentification to the api failed. You may have to
|
||||
* check into config or .env file for your service credentials
|
||||
*
|
||||
* @method static self methodNotAllowed()
|
||||
* This http method is not allowed
|
||||
*
|
||||
* @method static self wrongTimeStamp()
|
||||
* The timestamp given is wrong. This would happen in case if
|
||||
* a replay attack scenario. Timestamps are provided in headers
|
||||
* and in the http body
|
||||
*
|
||||
* @method static self missingParameter()
|
||||
* The request is missing some parameters
|
||||
*
|
||||
* @method static self throttleRequestsException()
|
||||
* Too many requests have been attempted. The is a throttle security.
|
||||
* Normally you should not trigger this.
|
||||
* If this happens fill a ticket on https://supportweb.ldc.fr
|
||||
* with some technical details
|
||||
*
|
||||
* @method static self authorizationException()
|
||||
* You are maybe trying to access data that is out of your range.
|
||||
* This should not happen normally, it is here to allow you to handle this case.
|
||||
* If this happens fill a ticket on https://supportweb.ldc.fr
|
||||
* with some technical details
|
||||
*
|
||||
*/
|
||||
class ApiError extends BaseEnumRoutable
|
||||
{
|
||||
/**
|
||||
* Valeurs des possibilités de cet énumération (value)
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return [
|
||||
'modelNotFound' => 101,
|
||||
'validationFailed' => 102,
|
||||
'apiAuthFailed' => 119,
|
||||
'methodNotAllowed' => 150,
|
||||
'wrongTimeStamp' => 151,
|
||||
'missingParameter' => 400,
|
||||
'authorizationException' => 403,
|
||||
'throttleRequestsException' => 429
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Libellés des possibilités de cet énumération (label)
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function labels(): array
|
||||
{
|
||||
return [
|
||||
'modelNotFound' => '%s introuvable.',
|
||||
'validationFailed' => 'Impossible de valider les données',
|
||||
'apiAuthFailed' => 'Echec de l\'authentification client à l\'Api LDC-CRM pour ce service',
|
||||
'methodNotAllowed' => 'This method is not allowed for this request',
|
||||
'wrongTimeStamp' => 'Your request is malformed, please check timestamp header and parameter',
|
||||
'missingParameter' => 'The request is missing some parameters',
|
||||
'authorizationException' => 'You are not autorized to access this',
|
||||
'throttleRequestsException' => 'Throttle: too many request have been attempted, please retry later'
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Kwaadpepper\Enum\BaseEnumRoutable;
|
||||
|
||||
/**
|
||||
* @method static self OK()
|
||||
* @method static self KO()
|
||||
*
|
||||
* @package LDCCrmClient
|
||||
* @subpackage enums
|
||||
*/
|
||||
class ApiStatus extends BaseEnumRoutable
|
||||
{
|
||||
}
|
||||
|
|
@ -2,29 +2,27 @@
|
|||
|
||||
namespace App\Exceptions\Api;
|
||||
|
||||
use App\Enums\ApiError;
|
||||
use Exception;
|
||||
use App\Enums\Api\ApiError;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* This would be thrown if any of the case
|
||||
* referenced in \App\Enums\ApiError would
|
||||
* occur within the crm
|
||||
* occur within flucollector
|
||||
*
|
||||
* On the client an ApiErrorException would
|
||||
* also be throw with the ApiError corresponding to
|
||||
* the situation
|
||||
*/
|
||||
class ApiErrorException extends Exception
|
||||
class ApiErrorException extends \RuntimeException
|
||||
{
|
||||
/**
|
||||
* Api Error
|
||||
* This value makes the error more explicit.
|
||||
* Handling these errors are normal as inputs or
|
||||
* request may be undesired or refused by the crm.
|
||||
* request may be undesired or refused by flucollector.
|
||||
*
|
||||
* @var \App\Enums\ApiError
|
||||
* @var \App\Enums\Api\ApiError
|
||||
*/
|
||||
protected $error;
|
||||
|
||||
|
|
@ -38,7 +36,7 @@ class ApiErrorException extends Exception
|
|||
protected $message;
|
||||
|
||||
/**
|
||||
* This is the http code returned by the crm.
|
||||
* This is the http code returned by flucollector.
|
||||
* This value could be used to handle errors.
|
||||
* But please take in consideration $error first
|
||||
*
|
||||
|
|
@ -49,12 +47,12 @@ class ApiErrorException extends Exception
|
|||
/**
|
||||
* Create a new exception base on ApiError enum.
|
||||
*
|
||||
* @param ApiError $error
|
||||
* @param integer $httpCode
|
||||
* @param string $message
|
||||
* @param Throwable|null $previous
|
||||
* @param \App\Enums\Api\ApiError $error
|
||||
* @param integer $httpCode
|
||||
* @param string $message
|
||||
* @param \Throwable|null $previous
|
||||
*/
|
||||
public function __construct(ApiError $error, int $httpCode = 400, string $message = '', Throwable $previous = null)
|
||||
public function __construct(ApiError $error, int $httpCode = 400, string $message = '', \Throwable $previous = null)
|
||||
{
|
||||
$this->error = $error;
|
||||
$this->message = $message;
|
||||
|
|
@ -69,7 +67,7 @@ class ApiErrorException extends Exception
|
|||
/**
|
||||
* Get the Api Error
|
||||
*
|
||||
* @return ApiError
|
||||
* @return \App\Enums\Api\ApiError
|
||||
*/
|
||||
public function getApiError(): ApiError
|
||||
{
|
||||
|
|
@ -95,7 +93,7 @@ class ApiErrorException extends Exception
|
|||
public function report()
|
||||
{
|
||||
// @codeCoverageIgnoreStart
|
||||
Log::debug(sprintf('CRM API: %s', $this->getMessage()));
|
||||
Log::debug(sprintf('FluxCollector API: %s', $this->getMessage()));
|
||||
// @codeCoverageIgnoreEnd
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
namespace App\Exceptions\Api;
|
||||
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
|
|
@ -10,7 +9,7 @@ use Illuminate\Support\Facades\Log;
|
|||
* The request could not be handled. You may dump any value you can
|
||||
* get before submitting a ticket to https://supportweb.ldc.fr
|
||||
*/
|
||||
class ApplicationException extends Exception
|
||||
class ApplicationException extends \RuntimeException
|
||||
{
|
||||
/**
|
||||
* This is used by laravel only.
|
||||
|
|
|
|||
|
|
@ -2,32 +2,39 @@
|
|||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use App\Enums\Api\ApiError;
|
||||
use App\Enums\Api\ApiStatus;
|
||||
use App\Http\Resources\Api\ApiResponse;
|
||||
use App\Lib\ApiHelper;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Auth\AuthenticationException;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\Exceptions\ThrottleRequestsException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
|
||||
use Throwable;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
|
||||
|
||||
class Handler extends ExceptionHandler
|
||||
{
|
||||
/**
|
||||
* A list of exception types with their corresponding custom log levels.
|
||||
*
|
||||
* @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
|
||||
*/
|
||||
protected $levels = [];
|
||||
|
||||
/**
|
||||
* A list of the exception types that are not reported.
|
||||
*
|
||||
* @var array<int, class-string<\Throwable>>
|
||||
* @var array
|
||||
*/
|
||||
protected $dontReport = [];
|
||||
protected $dontReport = [
|
||||
ApiErrorException::class,
|
||||
RedirectTo::class
|
||||
];
|
||||
|
||||
/**
|
||||
* A list of the inputs that are never flashed to the session on validation exceptions.
|
||||
* A list of the inputs that are never flashed for validation exceptions.
|
||||
*
|
||||
* @var array<int, string>
|
||||
* @var array
|
||||
*/
|
||||
protected $dontFlash = [
|
||||
'current_password',
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
|
|
@ -37,12 +44,132 @@ class Handler extends ExceptionHandler
|
|||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register()
|
||||
public function register(): void
|
||||
{
|
||||
$this->reportable(function (Throwable $e) {
|
||||
$this->reportable(function (\Throwable $e) {
|
||||
if (app()->bound('sentry')) {
|
||||
app('sentry')->captureException($e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Render an exception into an HTTP response.
|
||||
*
|
||||
* @param mixed $request
|
||||
* @param \Throwable $e
|
||||
* @return \Symfony\Component\HttpFoundation\Response
|
||||
*/
|
||||
public function render(mixed $request, \Throwable $e): Response
|
||||
{
|
||||
if (ApiHelper::isRequestForApi($request) and $request->isJson()) {
|
||||
return $this->handleApiException($request, $e);
|
||||
} //end if
|
||||
// @codeCoverageIgnoreStart
|
||||
return parent::render($request, $e);
|
||||
// @codeCoverageIgnoreEnd
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a json response for any apiV4 error case.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Throwable $e
|
||||
* @return \Illuminate\Http\JsonResponse
|
||||
*/
|
||||
private function handleApiException(Request $request, \Throwable $e): JsonResponse
|
||||
{
|
||||
switch (get_class($e)) {
|
||||
case AuthenticationException::class:
|
||||
/** @var AuthenticationException $e */
|
||||
return $this->getReponse(
|
||||
$request,
|
||||
401,
|
||||
ApiError::apiAuthFailed->value(),
|
||||
sprintf('%s, %s', ApiError::apiAuthFailed->label(), $e->getMessage())
|
||||
);
|
||||
case MethodNotAllowedHttpException::class:
|
||||
/** @var MethodNotAllowedHttpException $e */
|
||||
return $this->getReponse(
|
||||
$request,
|
||||
$e->getStatusCode(),
|
||||
ApiError::methodNotAllowed->value(),
|
||||
sprintf('%s, %s', ApiError::methodNotAllowed->label(), $e->getMessage())
|
||||
);
|
||||
case ValidationException::class:
|
||||
/** @var ValidationException $e */
|
||||
return $this->getReponse(
|
||||
$request,
|
||||
$e->status,
|
||||
ApiError::validationFailed->value(),
|
||||
sprintf(ApiError::validationFailed->label(), $e->getMessage()),
|
||||
['errors' => $e->errors()]
|
||||
);
|
||||
case ModelNotFoundException::class:
|
||||
/** @var ModelNotFoundException $e */
|
||||
return $this->getReponse(
|
||||
$request,
|
||||
404,
|
||||
ApiError::modelNotFound->value(),
|
||||
sprintf(
|
||||
ApiError::modelNotFound->label(),
|
||||
\array_slice(explode('\\', $e->getModel()), -1)[0]
|
||||
)
|
||||
);
|
||||
case ApiErrorException::class:
|
||||
/** @var ApiErrorException $e */
|
||||
return $this->getReponse(
|
||||
$request,
|
||||
$e->getStatusCode(),
|
||||
$e->getCode(),
|
||||
$e->getMessage()
|
||||
);
|
||||
case ThrottleRequestsException::class:
|
||||
/** @var ThrottleRequestsException $e */
|
||||
return $this->getReponse(
|
||||
$request,
|
||||
429,
|
||||
ApiError::throttleRequestsException->value(),
|
||||
ApiError::throttleRequestsException->label()
|
||||
);
|
||||
case AuthorizationException::class:
|
||||
/** @var AuthorizationException $e */
|
||||
return $this->getReponse(
|
||||
$request,
|
||||
403,
|
||||
ApiError::authorizationException->value(),
|
||||
ApiError::authorizationException->label()
|
||||
);
|
||||
} //end switch
|
||||
// @codeCoverageIgnoreStart
|
||||
if (config('app.env') === 'testing') {
|
||||
// phpcs:ignore Squiz.PHP.DiscouragedFunctions.Found
|
||||
print_r((string)$e);
|
||||
}
|
||||
return $this->getReponse($request, 500, \intval($e->getCode()), $e->getMessage());
|
||||
// @codeCoverageIgnoreEnd
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate an Api json response.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param integer $httpCode
|
||||
* @param integer $apiCode
|
||||
* @param string $message
|
||||
* @param array $data
|
||||
* @return \Illuminate\Http\JsonResponse
|
||||
*/
|
||||
private static function getReponse(
|
||||
Request $request,
|
||||
int $httpCode,
|
||||
int $apiCode,
|
||||
string $message,
|
||||
array $data = []
|
||||
): JsonResponse {
|
||||
return (new ApiResponse(
|
||||
(object)array_merge($data, ['message' => $message, 'code' => $apiCode]),
|
||||
ApiStatus::KO
|
||||
))->toResponse($request)->setStatusCode($httpCode);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
19
app/Http/Controllers/Api/ApiController.php
Normal file
19
app/Http/Controllers/Api/ApiController.php
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class ApiController extends Controller
|
||||
{
|
||||
/**
|
||||
* Just returns HTTP 200 response.
|
||||
*
|
||||
* @return \Illuminate\Http\JsonResponse
|
||||
*/
|
||||
public function ping(): JsonResponse
|
||||
{
|
||||
return response()->json();
|
||||
}
|
||||
}
|
||||
63
app/Http/Controllers/Api/XmlIncoController.php
Normal file
63
app/Http/Controllers/Api/XmlIncoController.php
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Api\XmlInco\SearchRequest;
|
||||
use App\Http\Resources\Api\XmlListResource;
|
||||
use App\Http\Resources\XmlIncoResource;
|
||||
use App\Models\Service;
|
||||
use App\Models\XmlInco;
|
||||
use Illuminate\Contracts\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class XmlIncoController extends Controller
|
||||
{
|
||||
/**
|
||||
* Returns all service questions.
|
||||
*
|
||||
* @param \App\Http\Requests\Api\XmlInco\SearchRequest $request
|
||||
* @param \App\Models\Service $service
|
||||
* @return \Illuminate\Http\Resources\Json\ResourceCollection
|
||||
*/
|
||||
public function search(SearchRequest $request, Service $service): ResourceCollection
|
||||
{
|
||||
return new XmlListResource($service->arcadiaBrand->xmlIncos()
|
||||
->where(fn (Builder $q) => $this->searchQuery(
|
||||
$q,
|
||||
$request->search,
|
||||
null,
|
||||
'id',
|
||||
'name'
|
||||
))->limit(20)->get(['id', 'name']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ids list of updated resources since a specific date
|
||||
*
|
||||
* @param \App\Models\Service $service
|
||||
* @param \Illuminate\Support\Carbon $since
|
||||
* @return \Illuminate\Http\Resources\Json\ResourceCollection
|
||||
*/
|
||||
public function getIdListSince(Service $service, Carbon $since): ResourceCollection
|
||||
{
|
||||
return new XmlListResource(
|
||||
$service->arcadiaBrand->xmlIncos()
|
||||
->whereDate('updated_at', '>=', $since)->get(['id']),
|
||||
null,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show Xml Inco resource
|
||||
*
|
||||
* @param \App\Models\XmlInco $xml_inco
|
||||
* @return \App\Http\Resources\XmlIncoResource
|
||||
*/
|
||||
public function show(XmlInco $xml_inco): XmlIncoResource
|
||||
{
|
||||
return new XmlIncoResource($xml_inco);
|
||||
}
|
||||
}
|
||||
|
|
@ -42,6 +42,9 @@ class Kernel extends HttpKernel
|
|||
|
||||
'api' => [
|
||||
\Illuminate\Routing\Middleware\ThrottleRequests::class . ':api',
|
||||
\App\Http\Middleware\JsonOnly::class,
|
||||
\App\Http\Middleware\ApiResponse::class,
|
||||
\App\Http\Middleware\ApiCheckTimeStamps::class,
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
];
|
||||
|
|
|
|||
43
app/Http/Middleware/ApiCheckTimeStamps.php
Normal file
43
app/Http/Middleware/ApiCheckTimeStamps.php
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Enums\Api\ApiError;
|
||||
use App\Exceptions\Api\ApiErrorException;
|
||||
use App\Lib\ApiHelper;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Check Http Header Timestamp with request timestamp
|
||||
* to prevent replay attacks
|
||||
* https://restfulapi.net/security-essentials/
|
||||
*/
|
||||
class ApiCheckTimeStamps
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
* @throws \App\Exceptions\Api\V4\ApiErrorException With ApiError::wrongTimeStamp
|
||||
* if timestamp has an incorrect
|
||||
* format or is timed out.
|
||||
*/
|
||||
public function handle(Request $request, \Closure $next): mixed
|
||||
{
|
||||
if (ApiHelper::isRequestForApi($request)) {
|
||||
if (!\is_string($request->timestamp) or !Carbon::hasFormat($request->timestamp, 'Y-m-d H:i:s')) {
|
||||
throw new ApiErrorException(ApiError::wrongTimeStamp);
|
||||
}
|
||||
if (
|
||||
Carbon::parse($request->timestamp, 'utc')
|
||||
->isBefore(Carbon::now('UTC')->subSeconds(config('api.timestampTimeout', 10)))
|
||||
) {
|
||||
throw new ApiErrorException(ApiError::wrongTimeStamp);
|
||||
}
|
||||
}
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
59
app/Http/Middleware/ApiResponse.php
Normal file
59
app/Http/Middleware/ApiResponse.php
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Enums\Api\ApiStatus;
|
||||
use App\Http\Resources\Api\ApiResponse as ApiResponseResource;
|
||||
use App\Models\Service;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ApiResponse
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
* @throws \ErrorException If the received response is not a JsonResponse.
|
||||
*/
|
||||
public function handle(Request $request, \Closure $next): mixed
|
||||
{
|
||||
/** @var \Illuminate\Http\JsonResponse $response */
|
||||
$response = $next($request);
|
||||
|
||||
if (\get_class($response) !== JsonResponse::class) {
|
||||
// @codeCoverageIgnoreStart
|
||||
throw new \ErrorException('All api responses should be json.');
|
||||
// @codeCoverageIgnoreEnd
|
||||
}
|
||||
|
||||
// Set no cache header.
|
||||
$response->header('Cache-Control', 'No-Store');
|
||||
|
||||
/** @var \App\Models\Service|null */
|
||||
if (\optional($service = app(Service::class))->id) {
|
||||
$service->incrementStat();
|
||||
}
|
||||
|
||||
/** @var object $data */
|
||||
$data = $response->getData();
|
||||
|
||||
/** Check if it's and Api Response. */
|
||||
if (
|
||||
gettype($data) === "object" and
|
||||
isset($data->status) and
|
||||
isset($data->data) and
|
||||
isset($data->version) and
|
||||
in_array($data->status, [ApiStatus::OK->value(), ApiStatus::KO->value()])
|
||||
) {
|
||||
/** Return direct ApiResponse */
|
||||
return $response;
|
||||
}
|
||||
|
||||
$status = intval($response->getStatusCode() / 100) == 2 ? ApiStatus::OK : ApiStatus::KO;
|
||||
|
||||
return $response->setData(new ApiResponseResource((object)$data, $status));
|
||||
}
|
||||
}
|
||||
27
app/Http/Middleware/JsonOnly.php
Normal file
27
app/Http/Middleware/JsonOnly.php
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class JsonOnly
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure $next
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(Request $request, \Closure $next): mixed
|
||||
{
|
||||
if (
|
||||
(!$request->isJson() or
|
||||
!$request->expectsJson() or
|
||||
is_null(json_decode($request->getContent())))
|
||||
) {
|
||||
abort(400, 'Invalid JSON');
|
||||
}
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
42
app/Http/Requests/Api/XmlInco/SearchRequest.php
Normal file
42
app/Http/Requests/Api/XmlInco/SearchRequest.php
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Requests\Api\XmlInco;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class SearchRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return auth('api')->check();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the data for validation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareForValidation()
|
||||
{
|
||||
$this->merge([
|
||||
'search' => is_string($this->search) ? strip_tags($this->search) : null
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string,\Illuminate\Contracts\Validation\ValidationRule|array|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'search' => 'required|string|min:1'
|
||||
];
|
||||
}
|
||||
}
|
||||
43
app/Http/Resources/Api/ApiResponse.php
Normal file
43
app/Http/Resources/Api/ApiResponse.php
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources\Api;
|
||||
|
||||
use App\Enums\Api\ApiStatus;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class ApiResponse extends JsonResource
|
||||
{
|
||||
/** @var \stdClass|null */
|
||||
protected $data;
|
||||
|
||||
/** @var \App\Enums\ApiStatus */
|
||||
protected $status;
|
||||
|
||||
/**
|
||||
* @param \stdClass|null $data
|
||||
* @param \App\Enums\Api\ApiStatus $status
|
||||
*/
|
||||
public function __construct(\stdClass|null $data = null, ApiStatus $status)
|
||||
{
|
||||
$this->status = $status;
|
||||
$this->data = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return array
|
||||
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
//phpcs:enable
|
||||
return [
|
||||
'status' => $this->status->value(),
|
||||
'data' => (array)($this->data ?? []),
|
||||
'version' => config('api.version')
|
||||
];
|
||||
}
|
||||
}
|
||||
59
app/Http/Resources/Api/XmlListResource.php
Normal file
59
app/Http/Resources/Api/XmlListResource.php
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources\Api;
|
||||
|
||||
use App\Models\XmlInco;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection as JsonResourceCollection;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class XmlListResource extends JsonResourceCollection
|
||||
{
|
||||
/** @var \Illuminate\Support\Collection<\App\Models\XmlInco> */
|
||||
protected $xmlIncoList = null;
|
||||
|
||||
/**
|
||||
* Send only ids
|
||||
*
|
||||
* @var boolean
|
||||
*/
|
||||
protected $onlyIds = false;
|
||||
|
||||
/**
|
||||
* Create a new resource instance.
|
||||
*
|
||||
* @param mixed $resource
|
||||
* @param \Illuminate\Support\Collection<\App\Models\XmlInco> $xmlIncoList
|
||||
* @param boolean $onlyIds
|
||||
* @return void
|
||||
* @phpcs:disable Squiz.Commenting.FunctionComment.IncorrectTypeHint
|
||||
*/
|
||||
public function __construct(mixed $resource, Collection $xmlIncoList = null, bool $onlyIds = false)
|
||||
{
|
||||
//phpcs:enable
|
||||
$this->xmlIncoList = $xmlIncoList;
|
||||
$this->onlyIds = $onlyIds;
|
||||
parent::__construct($resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Support\Collection
|
||||
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
|
||||
*/
|
||||
public function toArray(Request $request): \Illuminate\Support\Collection
|
||||
{
|
||||
//phpcs:enable
|
||||
return $this->collection->map(function (XmlInco $xml_inco) {
|
||||
if ($this->onlyIds) {
|
||||
return $xml_inco->id;
|
||||
}
|
||||
return [
|
||||
'id' => $xml_inco->id,
|
||||
'name' => $xml_inco->name
|
||||
];
|
||||
});
|
||||
}
|
||||
}
|
||||
44
app/Http/Resources/XmlIncoResource.php
Normal file
44
app/Http/Resources/XmlIncoResource.php
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
class XmlIncoResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* The resource instance.
|
||||
*
|
||||
* @var \App\Models\XmlInco
|
||||
*/
|
||||
public $resource;
|
||||
|
||||
/**
|
||||
* XmlInco columns to keep
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private array $skel = [
|
||||
'id', 'name', 'description', 'tips',
|
||||
'preparation_advices', 'sell_arguments',
|
||||
'allegations', 'ingredient_list', 'allergen_list',
|
||||
'nutritional_values', 'portion_amount', 'portion_type',
|
||||
'is_seasonal', 'updated_at'
|
||||
];
|
||||
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return array<string, mixed>
|
||||
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
|
||||
// phpcs:enable
|
||||
return Arr::only($this->resource->toArray(), $this->skel);
|
||||
}
|
||||
}
|
||||
|
|
@ -10,9 +10,9 @@ use Illuminate\Support\Facades\Route;
|
|||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Helper Class
|
||||
* Api Helper Class
|
||||
*/
|
||||
class Helper
|
||||
class ApiHelper
|
||||
{
|
||||
/**
|
||||
* Package infos
|
||||
|
|
@ -21,6 +21,20 @@ class Helper
|
|||
*/
|
||||
private static $packageInfos;
|
||||
|
||||
/**
|
||||
* Tells if the request is within api routes.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return boolean
|
||||
*/
|
||||
public static function isRequestForApi(Request $request): bool
|
||||
{
|
||||
// * Small hack to ensure to know if route is From APIv2.
|
||||
$routeName = static::getRouteName($request) ??
|
||||
(strpos($request->path(), 'api') === 0 ? 'api.' : null) ?? 'none';
|
||||
return strpos($routeName, 'api.') === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to get current route name
|
||||
*
|
||||
|
|
@ -99,8 +113,12 @@ class Helper
|
|||
* @return string request signature
|
||||
* @throws ApplicationException If an error occurs.
|
||||
*/
|
||||
public static function signRequest(#[\SensitiveParameter] string $secret, string $uri, string $method, array $parameters): string
|
||||
{
|
||||
public static function signRequest(
|
||||
#[\SensitiveParameter] string $secret,
|
||||
string $uri,
|
||||
string $method,
|
||||
array $parameters
|
||||
): string {
|
||||
try {
|
||||
$uri = collect(\parse_url($uri));
|
||||
$method = \strtolower($method);
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
<?php
|
||||
|
||||
namespace App\Lib;
|
||||
namespace App\Lib\Helpers;
|
||||
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
|
|
|||
|
|
@ -10,6 +10,11 @@ use Rennokki\QueryCache\Traits\QueryCacheable;
|
|||
/**
|
||||
* @property-read integer $id The arcadia brand id.
|
||||
* @property-read string $label The arcadia brand name.
|
||||
*
|
||||
* @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\Service> $services
|
||||
* The Services for the ArcadiaBrand.
|
||||
* @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\XmlInco> $xmlIncos
|
||||
* The XmlIncos for the ArcadiaBrand.
|
||||
* @package App\Models
|
||||
*/
|
||||
class ArcadiaBrand extends Model
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
namespace App\Models;
|
||||
|
||||
use App\Jobs\SetServiceStats;
|
||||
use App\Lib\Helper;
|
||||
use App\Lib\ApiHelper;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
|
|
@ -14,6 +14,19 @@ use Illuminate\Support\Facades\Crypt;
|
|||
use Illuminate\Support\Str;
|
||||
use Rennokki\QueryCache\Traits\QueryCacheable;
|
||||
|
||||
/**
|
||||
* @property integer $id The service id.
|
||||
* @property string $name Le nom du service de la marque.
|
||||
* @property string $bearer_token Le Token pour identifier le service.
|
||||
* @property string $bearer_pwd La clé du service pour l'Api.
|
||||
* @property string $bearer_token_date Date de génération des clés bearer du services
|
||||
* @property integer $arcadia_brand_id Foreign key Arcadia brand.
|
||||
*
|
||||
* @property-read \App\Models\ArcadiaBrand $arcadiaBrand The Arcadia Brand that owns the Service.
|
||||
* @property-read \Illuminate\Database\Eloquent\Collection<\App\Models\ServiceStat> $servicesStats
|
||||
* The Services Stats for the Service.
|
||||
* @package App\Models
|
||||
*/
|
||||
class Service extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
|
@ -212,7 +225,7 @@ class Service extends Model
|
|||
$data = (\is_array($data) and \json_last_error() === \JSON_ERROR_NONE) ?
|
||||
array_replace_recursive($request->all(), $data) : $request->all();
|
||||
|
||||
$calculatedHash = Helper::signRequest(
|
||||
$calculatedHash = ApiHelper::signRequest(
|
||||
$this->bearer_pwd,
|
||||
$request->getUri(),
|
||||
$request->getMethod(),
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
namespace App\Providers;
|
||||
|
||||
use App\Enums\Users\RoleEnum;
|
||||
use App\Lib\Helper;
|
||||
use App\Lib\ApiHelper;
|
||||
use App\Models\Service;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
|
|
@ -42,7 +42,7 @@ class AuthServiceProvider extends ServiceProvider
|
|||
}
|
||||
|
||||
// * Si la route actuelle n'as pas de nom alors on refuse de la traiter.
|
||||
if (!(Helper::getRoute($request))) {
|
||||
if (!(ApiHelper::getRoute($request))) {
|
||||
// @codeCoverageIgnoreStart
|
||||
return null;
|
||||
// @codeCoverageIgnoreEnd
|
||||
|
|
|
|||
|
|
@ -3,9 +3,11 @@
|
|||
namespace App\Providers;
|
||||
|
||||
use App\Models\User;
|
||||
use Carbon\Exceptions\InvalidFormatException;
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
|
|
@ -46,6 +48,13 @@ class RouteServiceProvider extends ServiceProvider
|
|||
});
|
||||
|
||||
Route::model('user', User::class);
|
||||
Route::bind('since', function (string $urlDate) {
|
||||
try {
|
||||
return Carbon::parse($urlDate);
|
||||
} catch (InvalidFormatException) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
<?php
|
||||
|
||||
use App\Lib\Helper;
|
||||
use App\Lib\ApiHelper;
|
||||
|
||||
return [
|
||||
/**
|
||||
* Api versions
|
||||
** this value is sent in response
|
||||
*/
|
||||
'version' => Helper::getPackageInfo()['version'],
|
||||
'version' => ApiHelper::getPackageInfo()['version'],
|
||||
|
||||
/**
|
||||
* Timestamp timeout in seconds
|
||||
|
|
|
|||
|
|
@ -46,6 +46,10 @@ return [
|
|||
// ! Remplacer "users" par le model authenticable voulu
|
||||
'provider' => 'users',
|
||||
],
|
||||
|
||||
'api' => [
|
||||
'driver' => 'api-hmac'
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
|
|
|
|||
|
|
@ -1 +1,17 @@
|
|||
<?php
|
||||
|
||||
use App\Http\Controllers\Api\ApiController;
|
||||
use App\Http\Controllers\Api\XmlIncoController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
// * PUBLIC
|
||||
Route::get('/ping', [ApiController::class, 'ping'])->name('ping');
|
||||
|
||||
// * PRIVATE
|
||||
Route::middleware('auth:api')->group(function () {
|
||||
Route::prefix('xml_incos')->name('xml_incos.')->group(function () {
|
||||
Route::get('search', [XmlIncoController::class, 'search'])->name('search');
|
||||
Route::get('update-since/{since}', [XmlIncoController::class, 'getIdListSince'])->name('since');
|
||||
Route::get('{xml_inco}', [XmlIncoController::class, 'show'])->name('show');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue