Skip to content

Commit

Permalink
Merge pull request #65 from XetaIO/manage-419-error
Browse files Browse the repository at this point in the history
Add a custom message with the 419 CSRF error & Remove $dontReport as …
  • Loading branch information
Xety committed Apr 7, 2022
2 parents aa81bca + 7f13b9f commit 25397b8
Showing 1 changed file with 23 additions and 16 deletions.
39 changes: 23 additions & 16 deletions app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
*
Expand Down Expand Up @@ -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
Expand All @@ -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.');
Expand Down

0 comments on commit 25397b8

Please sign in to comment.