firefly-iii/app/Exceptions/Handler.php

282 lines
10 KiB
PHP
Raw Normal View History

<?php
2018-05-11 03:08:34 -05:00
2017-10-21 01:40:00 -05:00
/**
* Handler.php
2020-01-28 01:44:57 -06:00
* Copyright (c) 2019 james@firefly-iii.org
2017-10-21 01:40:00 -05:00
*
* This file is part of Firefly III (https://github.com/firefly-iii).
2017-10-21 01:40:00 -05:00
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
2017-10-21 01:40:00 -05:00
*
* This program is distributed in the hope that it will be useful,
2017-10-21 01:40:00 -05:00
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
2017-10-21 01:40:00 -05:00
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
2017-10-21 01:40:00 -05:00
*/
2017-09-14 10:40:02 -05:00
2018-05-11 03:08:34 -05:00
declare(strict_types=1);
namespace FireflyIII\Exceptions;
2015-02-05 21:39:52 -06:00
2017-09-12 15:14:43 -05:00
use ErrorException;
use FireflyIII\Jobs\MailError;
2023-11-05 01:15:17 -06:00
use FireflyIII\Models\ObjectGroup;
2018-02-17 07:14:26 -06:00
use Illuminate\Auth\AuthenticationException;
2021-10-02 06:28:56 -05:00
use Illuminate\Contracts\Foundation\Application;
2022-06-09 23:00:01 -05:00
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
2021-10-02 06:28:56 -05:00
use Illuminate\Http\RedirectResponse;
2020-07-31 05:45:02 -05:00
use Illuminate\Http\Request;
2021-10-02 06:28:56 -05:00
use Illuminate\Routing\Redirector;
2021-04-07 00:28:43 -05:00
use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Arr;
2018-07-15 03:00:08 -05:00
use Illuminate\Validation\ValidationException as LaravelValidationException;
2021-04-07 07:18:43 -05:00
use Laravel\Passport\Exceptions\OAuthServerException as LaravelOAuthException;
2021-05-28 16:11:12 -05:00
use League\OAuth2\Server\Exception\OAuthServerException;
2022-09-04 06:31:46 -05:00
use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
2022-12-29 12:41:57 -06:00
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
2021-04-07 23:50:00 -05:00
use Symfony\Component\HttpKernel\Exception\HttpException;
2022-06-23 02:33:43 -05:00
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
2021-05-28 16:11:12 -05:00
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
2020-06-06 15:25:52 -05:00
use Throwable;
2021-03-21 03:15:40 -05:00
2017-12-17 07:30:53 -06:00
/**
* Class Handler
*
2017-12-17 07:30:53 -06:00
*/
2015-02-11 00:35:10 -06:00
class Handler extends ExceptionHandler
{
/**
2022-12-31 06:32:42 -06:00
* @var array<int, class-string<Throwable>>
*/
protected $dontReport
= [
2021-04-03 06:19:11 -05:00
AuthenticationException::class,
LaravelValidationException::class,
2021-04-04 08:53:17 -05:00
NotFoundHttpException::class,
2021-04-07 00:28:43 -05:00
OAuthServerException::class,
2021-04-07 07:18:43 -05:00
LaravelOAuthException::class,
2021-04-07 00:28:43 -05:00
TokenMismatchException::class,
2021-05-28 16:11:12 -05:00
HttpException::class,
2022-12-29 12:41:57 -06:00
SuspiciousOperationException::class,
2023-01-08 09:34:34 -06:00
BadHttpHeaderException::class,
];
2016-02-11 07:17:11 -06:00
/**
2017-09-12 15:14:43 -05:00
* Render an exception into an HTTP response.
2016-02-11 07:17:11 -06:00
*
2023-06-21 05:34:58 -05:00
* @param Request $request
* @param Throwable $e
2019-08-17 03:46:55 -05:00
*
* @return mixed
2021-05-24 01:50:17 -05:00
* @throws Throwable
2016-02-11 07:17:11 -06:00
*/
2021-04-03 06:19:11 -05:00
public function render($request, Throwable $e)
2016-02-11 07:17:11 -06:00
{
2023-01-11 01:13:52 -06:00
$expectsJson = $request->expectsJson();
// if the user requests anything /api/, assume the user wants to see JSON.
if (str_starts_with($request->getRequestUri(), '/api/')) {
2023-10-29 00:33:43 -05:00
app('log')->debug('API endpoint, always assume user wants JSON.');
2023-01-11 01:13:52 -06:00
$expectsJson = true;
}
2023-10-29 00:33:43 -05:00
app('log')->debug('Now in Handler::render()');
2023-01-11 01:13:52 -06:00
if ($e instanceof LaravelValidationException && $expectsJson) {
2018-02-13 11:24:06 -06:00
// ignore it: controller will handle it.
2023-10-29 00:33:43 -05:00
app('log')->debug(sprintf('Return to parent to handle LaravelValidationException(%d)', $e->status));
2021-04-03 06:19:11 -05:00
return parent::render($request, $e);
2018-02-13 11:24:06 -06:00
}
2023-01-11 01:13:52 -06:00
if ($e instanceof NotFoundHttpException && $expectsJson) {
// JSON error:
2023-10-29 00:33:43 -05:00
app('log')->debug('Return JSON not found error.');
return response()->json(['message' => 'Resource not found', 'exception' => 'NotFoundHttpException'], 404);
}
2018-02-17 07:14:26 -06:00
2023-01-11 01:13:52 -06:00
if ($e instanceof AuthenticationException && $expectsJson) {
// somehow Laravel handler does not catch this:
2023-10-29 00:33:43 -05:00
app('log')->debug('Return JSON unauthenticated error.');
2018-02-17 07:14:26 -06:00
return response()->json(['message' => 'Unauthenticated', 'exception' => 'AuthenticationException'], 401);
}
2023-01-11 01:13:52 -06:00
if ($e instanceof OAuthServerException && $expectsJson) {
2023-10-29 00:33:43 -05:00
app('log')->debug('Return JSON OAuthServerException.');
// somehow Laravel handler does not catch this:
2021-04-03 06:19:11 -05:00
return response()->json(['message' => $e->getMessage(), 'exception' => 'OAuthServerException'], 401);
}
2022-10-30 08:24:10 -05:00
if ($e instanceof BadRequestHttpException) {
2023-10-29 00:33:43 -05:00
app('log')->debug('Return JSON BadRequestHttpException.');
2022-06-23 02:33:43 -05:00
return response()->json(['message' => $e->getMessage(), 'exception' => 'BadRequestHttpException'], 400);
}
if ($e instanceof BadHttpHeaderException) {
// is always API exception.
2023-10-29 00:33:43 -05:00
app('log')->debug('Return JSON BadHttpHeaderException.');
2022-06-23 02:33:43 -05:00
return response()->json(['message' => $e->getMessage(), 'exception' => 'BadHttpHeaderException'], $e->statusCode);
}
2023-01-11 01:13:52 -06:00
if ($expectsJson) {
2022-06-23 02:33:43 -05:00
$errorCode = 500;
2022-10-30 08:24:10 -05:00
$errorCode = $e instanceof MethodNotAllowedHttpException ? 405 : $errorCode;
2022-06-23 02:33:43 -05:00
2023-11-05 01:15:17 -06:00
$isDebug = (bool) config('app.debug', false);
if ($isDebug) {
2023-10-29 00:33:43 -05:00
app('log')->debug(sprintf('Return JSON %s with debug.', get_class($e)));
return response()->json(
[
2021-04-03 06:19:11 -05:00
'message' => $e->getMessage(),
'exception' => get_class($e),
'line' => $e->getLine(),
'file' => $e->getFile(),
'trace' => $e->getTrace(),
],
2022-06-23 02:33:43 -05:00
$errorCode
);
}
2023-10-29 00:33:43 -05:00
app('log')->debug(sprintf('Return JSON %s.', get_class($e)));
2021-03-21 03:15:40 -05:00
return response()->json(
2022-06-23 02:33:43 -05:00
['message' => sprintf('Internal Firefly III Exception: %s', $e->getMessage()), 'exception' => get_class($e)],
$errorCode
2021-03-21 03:15:40 -05:00
);
2018-02-10 02:57:56 -06:00
}
2021-04-03 06:19:11 -05:00
if ($e instanceof NotFoundHttpException) {
2023-10-29 00:33:43 -05:00
app('log')->debug('Refer to GracefulNotFoundHandler');
2019-07-31 23:22:07 -05:00
$handler = app(GracefulNotFoundHandler::class);
2021-04-03 06:19:11 -05:00
return $handler->render($request, $e);
2019-07-31 23:22:07 -05:00
}
2017-09-12 15:14:43 -05:00
2022-06-09 23:00:01 -05:00
// special view for database errors with extra instructions
2022-10-30 08:24:10 -05:00
if ($e instanceof QueryException) {
2023-10-29 00:33:43 -05:00
app('log')->debug('Return Firefly III database exception view.');
2022-06-09 23:00:01 -05:00
$isDebug = config('app.debug');
return response()->view('errors.DatabaseException', ['exception' => $e, 'debug' => $isDebug], 500);
}
2023-01-11 01:13:52 -06:00
if ($e instanceof FireflyException || $e instanceof ErrorException || $e instanceof OAuthServerException) {
2023-10-29 00:33:43 -05:00
app('log')->debug('Return Firefly III error view.');
2023-01-11 01:13:52 -06:00
$isDebug = config('app.debug');
return response()->view('errors.FireflyException', ['exception' => $e, 'debug' => $isDebug], 500);
}
2023-10-29 00:33:43 -05:00
app('log')->debug(sprintf('Error "%s" has no Firefly III treatment, parent will handle.', get_class($e)));
2017-09-12 15:14:43 -05:00
2021-04-03 06:19:11 -05:00
return parent::render($request, $e);
2015-02-11 00:35:10 -06:00
}
2016-09-15 23:40:45 -05:00
/**
2017-09-12 15:14:43 -05:00
* Report or log an exception.
2016-10-06 22:44:21 -05:00
*
2023-06-21 05:34:58 -05:00
* @param Throwable $e
2017-11-17 22:46:19 -06:00
*
2021-03-21 03:15:40 -05:00
* @return void
2021-04-03 06:19:11 -05:00
* @throws Throwable
2017-12-22 11:32:43 -06:00
*
2016-09-15 23:40:45 -05:00
*/
public function report(Throwable $e)
2016-09-15 23:40:45 -05:00
{
2023-11-05 01:15:17 -06:00
$doMailError = (bool) config('firefly.send_error_message');
if ($this->shouldntReportLocal($e) || !$doMailError) {
parent::report($e);
return;
2017-09-12 15:14:43 -05:00
}
$userData = [
'id' => 0,
'email' => 'unknown@example.com',
];
if (auth()->check()) {
$userData['id'] = auth()->user()->id;
$userData['email'] = auth()->user()->email;
}
2022-03-06 09:03:52 -06:00
2023-01-02 23:48:53 -06:00
$headers = request()->headers->all();
2022-03-06 09:03:52 -06:00
$data = [
'class' => get_class($e),
'errorMessage' => $e->getMessage(),
'time' => date('r'),
'stackTrace' => $e->getTraceAsString(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'code' => $e->getCode(),
'version' => config('firefly.version'),
'url' => request()->fullUrl(),
'userAgent' => request()->userAgent(),
'json' => request()->acceptsJson(),
2022-04-03 05:38:17 -05:00
'method' => request()->method(),
2022-03-06 09:03:52 -06:00
'headers' => $headers,
];
// create job that will mail.
$ipAddress = request()->ip() ?? '0.0.0.0';
2022-12-29 12:41:57 -06:00
$job = new MailError($userData, (string)config('firefly.site_owner'), $ipAddress, $data);
dispatch($job);
parent::report($e);
2016-09-15 23:40:45 -05:00
}
2023-06-21 05:34:58 -05:00
/**
* @param Throwable $e
*
* @return bool
*/
private function shouldntReportLocal(Throwable $e): bool
{
2023-11-04 08:18:49 -05:00
return null !== Arr::first(
2023-06-21 05:34:58 -05:00
$this->dontReport,
2023-11-04 08:18:49 -05:00
static function ($type) use ($e) {
2023-06-21 05:34:58 -05:00
return $e instanceof $type;
}
2023-11-04 08:18:49 -05:00
);
2023-06-21 05:34:58 -05:00
}
2021-10-02 06:28:56 -05:00
/**
* Convert a validation exception into a response.
*
2023-06-21 05:34:58 -05:00
* @param Request $request
* @param LaravelValidationException $exception
2021-10-02 06:28:56 -05:00
*
* @return Application|RedirectResponse|Redirector
*/
2023-06-21 05:34:58 -05:00
protected function invalid($request, LaravelValidationException $exception): Application | RedirectResponse | Redirector
2021-10-02 06:28:56 -05:00
{
// protect against open redirect when submitting invalid forms.
2021-10-02 23:05:30 -05:00
$previous = app('steam')->getSafePreviousUrl();
2021-10-02 06:28:56 -05:00
$redirect = $this->getRedirectUrl($exception);
return redirect($redirect ?? $previous)
->withInput(Arr::except($request->input(), $this->dontFlash))
->withErrors($exception->errors(), $request->input('_error_bag', $exception->errorBag));
}
/**
* Only return the redirectTo property from the exception if it is a valid URL. Return NULL otherwise.
*
2023-06-21 05:34:58 -05:00
* @param LaravelValidationException $exception
2021-10-02 06:28:56 -05:00
*
* @return string|null
*/
private function getRedirectUrl(LaravelValidationException $exception): ?string
{
if (null === $exception->redirectTo) {
return null;
}
$safe = route('index');
$previous = $exception->redirectTo;
$previousHost = parse_url($previous, PHP_URL_HOST);
$safeHost = parse_url($safe, PHP_URL_HOST);
return null !== $previousHost && $previousHost === $safeHost ? $previous : $safe;
}
2015-02-05 21:39:52 -06:00
}