From 7f13b9f0fbebb369a5bcfb9be8e1127876bc7886 Mon Sep 17 00:00:00 2001 From: Xety Date: Mon, 4 Apr 2022 19:14:38 +0200 Subject: [PATCH] Add a custom message with the 419 CSRF error & Remove $dontReport as Laravel9 has it in default now --- app/Exceptions/Handler.php | 39 ++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index fd969788..2d418e5d 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -3,24 +3,12 @@ use Illuminate\Auth\AuthenticationException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; +use Illuminate\Session\TokenMismatchException; use Illuminate\Support\Facades\Auth; use Throwable; class Handler extends ExceptionHandler { - /** - * A list of the exception types that should not be reported. - * - * @var array - */ - protected $dontReport = [ - \Illuminate\Auth\AuthenticationException::class, - \Illuminate\Auth\Access\AuthorizationException::class, - \Symfony\Component\HttpKernel\Exception\HttpException::class, - \Illuminate\Database\Eloquent\ModelNotFoundException::class, - \Illuminate\Session\TokenMismatchException::class, - \Illuminate\Validation\ValidationException::class - ]; /** * A list of the inputs that are never flashed for validation exceptions. @@ -46,6 +34,25 @@ public function report(Throwable $exception) parent::report($exception); } + /** + * Register the exception handling callbacks for the application. + * + * @return void + */ + public function register() + { + $this->reportable(function (Throwable $e) { + // + }); + + // Manage 419 csrf token expiration error + $this->renderable(function (\Exception $e) { + if ($e->getPrevious() instanceof TokenMismatchException) { + return back()->with('danger', 'You made too much time to validate the form ! Time to take a coffee !'); + }; + }); + } + /** * Render an exception into an HTTP response. * @@ -73,7 +80,7 @@ public function render($request, Throwable $exception) } /** - * Convert an authentication exception into an unauthenticated response. + * Convert an authentication exception into a response. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Auth\AuthenticationException $exception @@ -82,8 +89,8 @@ public function render($request, Throwable $exception) */ protected function unauthenticated($request, AuthenticationException $exception) { - return $request->expectsJson() - ? response()->json(['error' => 'Unauthenticated.'], 401) + return $this->shouldReturnJson($request, $exception) + ? response()->json(['message' => $exception->getMessage()], 401) : redirect() ->guest($exception->redirectTo() ?? route('users.auth.login')) ->with('danger', 'You don\'t have the permission to view this page.');