From c0c1608ad5fbf3c577e230a68cd6a2b7efeeb229 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Mon, 2 Oct 2023 09:35:06 +0200 Subject: [PATCH] Api calls ok --- app/Enums/Api/ApiError.php | 44 +++++ app/Enums/Api/ApiStatus.php | 13 ++ app/Enums/ApiError.php | 84 ---------- app/Enums/ApiStatus.php | 16 -- app/Exceptions/Api/ApiErrorException.php | 28 ++-- app/Exceptions/Api/ApplicationException.php | 3 +- app/Exceptions/Handler.php | 157 ++++++++++++++++-- app/Http/Controllers/Api/ApiController.php | 19 +++ .../Controllers/Api/XmlIncoController.php | 63 +++++++ app/Http/Kernel.php | 3 + app/Http/Middleware/ApiCheckTimeStamps.php | 43 +++++ app/Http/Middleware/ApiResponse.php | 59 +++++++ app/Http/Middleware/JsonOnly.php | 27 +++ .../Requests/Api/XmlInco/SearchRequest.php | 42 +++++ app/Http/Resources/Api/ApiResponse.php | 43 +++++ app/Http/Resources/Api/XmlListResource.php | 59 +++++++ app/Http/Resources/XmlIncoResource.php | 44 +++++ app/Lib/{Helper.php => ApiHelper.php} | 26 ++- app/Lib/Helpers/CollectionHelper.php | 2 +- app/Models/ArcadiaBrand.php | 5 + app/Models/Service.php | 17 +- app/Providers/AuthServiceProvider.php | 4 +- app/Providers/RouteServiceProvider.php | 9 + config/api.php | 4 +- config/auth.php | 4 + routes/api.php | 16 ++ 26 files changed, 691 insertions(+), 143 deletions(-) create mode 100644 app/Enums/Api/ApiError.php create mode 100644 app/Enums/Api/ApiStatus.php delete mode 100644 app/Enums/ApiError.php delete mode 100644 app/Enums/ApiStatus.php create mode 100644 app/Http/Controllers/Api/ApiController.php create mode 100644 app/Http/Controllers/Api/XmlIncoController.php create mode 100644 app/Http/Middleware/ApiCheckTimeStamps.php create mode 100644 app/Http/Middleware/ApiResponse.php create mode 100644 app/Http/Middleware/JsonOnly.php create mode 100644 app/Http/Requests/Api/XmlInco/SearchRequest.php create mode 100644 app/Http/Resources/Api/ApiResponse.php create mode 100644 app/Http/Resources/Api/XmlListResource.php create mode 100644 app/Http/Resources/XmlIncoResource.php rename app/Lib/{Helper.php => ApiHelper.php} (87%) diff --git a/app/Enums/Api/ApiError.php b/app/Enums/Api/ApiError.php new file mode 100644 index 0000000..0ebb93c --- /dev/null +++ b/app/Enums/Api/ApiError.php @@ -0,0 +1,44 @@ +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' + ]; +} diff --git a/app/Enums/Api/ApiStatus.php b/app/Enums/Api/ApiStatus.php new file mode 100644 index 0000000..01b5e65 --- /dev/null +++ b/app/Enums/Api/ApiStatus.php @@ -0,0 +1,13 @@ + 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' - ]; - } -} diff --git a/app/Enums/ApiStatus.php b/app/Enums/ApiStatus.php deleted file mode 100644 index c6a87a9..0000000 --- a/app/Enums/ApiStatus.php +++ /dev/null @@ -1,16 +0,0 @@ -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 } } diff --git a/app/Exceptions/Api/ApplicationException.php b/app/Exceptions/Api/ApplicationException.php index 06355f4..648ac54 100644 --- a/app/Exceptions/Api/ApplicationException.php +++ b/app/Exceptions/Api/ApplicationException.php @@ -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. diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 220b3d7..bd5eb5d 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -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, \Psr\Log\LogLevel::*> - */ - protected $levels = []; - /** * A list of the exception types that are not reported. * - * @var array> + * @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 + * @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); + } } diff --git a/app/Http/Controllers/Api/ApiController.php b/app/Http/Controllers/Api/ApiController.php new file mode 100644 index 0000000..3f2894b --- /dev/null +++ b/app/Http/Controllers/Api/ApiController.php @@ -0,0 +1,19 @@ +json(); + } +} diff --git a/app/Http/Controllers/Api/XmlIncoController.php b/app/Http/Controllers/Api/XmlIncoController.php new file mode 100644 index 0000000..46ad663 --- /dev/null +++ b/app/Http/Controllers/Api/XmlIncoController.php @@ -0,0 +1,63 @@ +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); + } +} diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 734332f..73bb9be 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -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, ], ]; diff --git a/app/Http/Middleware/ApiCheckTimeStamps.php b/app/Http/Middleware/ApiCheckTimeStamps.php new file mode 100644 index 0000000..a8c9783 --- /dev/null +++ b/app/Http/Middleware/ApiCheckTimeStamps.php @@ -0,0 +1,43 @@ +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); + } +} diff --git a/app/Http/Middleware/ApiResponse.php b/app/Http/Middleware/ApiResponse.php new file mode 100644 index 0000000..146eeb0 --- /dev/null +++ b/app/Http/Middleware/ApiResponse.php @@ -0,0 +1,59 @@ +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)); + } +} diff --git a/app/Http/Middleware/JsonOnly.php b/app/Http/Middleware/JsonOnly.php new file mode 100644 index 0000000..e2e734d --- /dev/null +++ b/app/Http/Middleware/JsonOnly.php @@ -0,0 +1,27 @@ +isJson() or + !$request->expectsJson() or + is_null(json_decode($request->getContent()))) + ) { + abort(400, 'Invalid JSON'); + } + return $next($request); + } +} diff --git a/app/Http/Requests/Api/XmlInco/SearchRequest.php b/app/Http/Requests/Api/XmlInco/SearchRequest.php new file mode 100644 index 0000000..7146b7f --- /dev/null +++ b/app/Http/Requests/Api/XmlInco/SearchRequest.php @@ -0,0 +1,42 @@ +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 + */ + public function rules(): array + { + return [ + 'search' => 'required|string|min:1' + ]; + } +} diff --git a/app/Http/Resources/Api/ApiResponse.php b/app/Http/Resources/Api/ApiResponse.php new file mode 100644 index 0000000..1fc5f44 --- /dev/null +++ b/app/Http/Resources/Api/ApiResponse.php @@ -0,0 +1,43 @@ +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') + ]; + } +} diff --git a/app/Http/Resources/Api/XmlListResource.php b/app/Http/Resources/Api/XmlListResource.php new file mode 100644 index 0000000..cde62ee --- /dev/null +++ b/app/Http/Resources/Api/XmlListResource.php @@ -0,0 +1,59 @@ + */ + 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 + ]; + }); + } +} diff --git a/app/Http/Resources/XmlIncoResource.php b/app/Http/Resources/XmlIncoResource.php new file mode 100644 index 0000000..837f340 --- /dev/null +++ b/app/Http/Resources/XmlIncoResource.php @@ -0,0 +1,44 @@ + + * @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass + */ + public function toArray(Request $request): array + { + + // phpcs:enable + return Arr::only($this->resource->toArray(), $this->skel); + } +} diff --git a/app/Lib/Helper.php b/app/Lib/ApiHelper.php similarity index 87% rename from app/Lib/Helper.php rename to app/Lib/ApiHelper.php index 6dbac03..f4f5ad6 100644 --- a/app/Lib/Helper.php +++ b/app/Lib/ApiHelper.php @@ -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); diff --git a/app/Lib/Helpers/CollectionHelper.php b/app/Lib/Helpers/CollectionHelper.php index a665a2f..b9e9ecd 100644 --- a/app/Lib/Helpers/CollectionHelper.php +++ b/app/Lib/Helpers/CollectionHelper.php @@ -1,6 +1,6 @@ $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 diff --git a/app/Models/Service.php b/app/Models/Service.php index b4c8e45..b24cf52 100644 --- a/app/Models/Service.php +++ b/app/Models/Service.php @@ -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(), diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 443fe49..110e428 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -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 diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index d3fcd23..22e35f8 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -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; + } + }); } /** diff --git a/config/api.php b/config/api.php index 8f8c4df..771d674 100644 --- a/config/api.php +++ b/config/api.php @@ -1,13 +1,13 @@ Helper::getPackageInfo()['version'], + 'version' => ApiHelper::getPackageInfo()['version'], /** * Timestamp timeout in seconds diff --git a/config/auth.php b/config/auth.php index 9cf409d..e291bd0 100644 --- a/config/auth.php +++ b/config/auth.php @@ -46,6 +46,10 @@ return [ // ! Remplacer "users" par le model authenticable voulu 'provider' => 'users', ], + + 'api' => [ + 'driver' => 'api-hmac' + ], ], /* diff --git a/routes/api.php b/routes/api.php index b3d9bbc..a2530b2 100644 --- a/routes/api.php +++ b/routes/api.php @@ -1 +1,17 @@ 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'); + }); +});