Passed
Push — feature/hr-admin-panel ( ceb1d1...dc17ad )
by Grant
09:09 queued 10s
created

Handler::render()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 27
rs 8.4444
cc 8
nc 6
nop 2
1
<?php
2
3
namespace App\Exceptions;
4
5
use Illuminate\Auth\Access\AuthorizationException;
6
use Illuminate\Auth\AuthenticationException;
7
use Illuminate\Database\Eloquent\ModelNotFoundException;
8
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
9
use Illuminate\Http\Exceptions\HttpResponseException;
10
use Illuminate\Session\TokenMismatchException;
11
use Illuminate\Support\Facades\Lang;
12
use Illuminate\Support\Facades\Log;
13
use Illuminate\Support\Facades\Request;
14
use Illuminate\Support\Facades\Auth;
15
use Illuminate\Validation\ValidationException;
16
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
17
18
class Handler extends ExceptionHandler
19
{
20
    /**
21
     * A list of the exception types that are not reported.
22
     *
23
     * @var array
24
     */
25
    protected $dontReport = [];
26
27
    /**
28
     * A list of the inputs that are never flashed for validation exceptions.
29
     *
30
     * @var array
31
     */
32
    protected $dontFlash = [
33
        'password',
34
        'password_confirmation',
35
        'current_password',
36
        'new_password',
37
        'new_password_confirmation',
38
    ];
39
40
    /**
41
     * OVERRIDE
42
     * A list of the internal exception types that should not be reported.
43
     *
44
     * @var array
45
     */
46
    protected $internalDontReport = [
47
        AuthenticationException::class,
48
        AuthorizationException::class,
49
        HttpResponseException::class,
50
        ModelNotFoundException::class,
51
        ValidationException::class,
52
    ];
53
54
    /**
55
     * Report or log an exception.
56
     *
57
     * @param  \Exception  $exception
58
     * @return void
59
     */
60
    public function report(\Exception $exception)
61
    {
62
        if ($exception instanceof TokenMismatchException) {
63
            $logData = [
64
                'requestToken' => request()->header('x-csrf-token'),
0 ignored issues
show
Bug introduced by
The function request was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

64
                'requestToken' => /** @scrutinizer ignore-call */ request()->header('x-csrf-token'),
Loading history...
65
                'sessionToken' => session()->token(),
0 ignored issues
show
Bug introduced by
The function session was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

65
                'sessionToken' => /** @scrutinizer ignore-call */ session()->token(),
Loading history...
66
                'session' => session()->all(),
67
                'user' => request()->user(),
68
                'requestUrl' => request()->url()
69
            ];
70
            $message = '419 CSRF Token Mismatch. ' . collect($logData)->toJson();
0 ignored issues
show
Bug introduced by
The function collect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

70
            $message = '419 CSRF Token Mismatch. ' . /** @scrutinizer ignore-call */ collect($logData)->toJson();
Loading history...
71
            Log::debug($message);
72
        }
73
74
        parent::report($exception);
75
    }
76
77
    /**
78
     * OVERRIDE
79
     * Get the default context variables for logging.
80
     *
81
     * @return array
82
     */
83
    protected function context()
84
    {
85
        try {
86
            return array_filter([
87
                'userId' => Auth::id(),
88
                'url' => Request::path(),
89
                'method' => Request::method(),
90
                'referer' => Request::header('referer', '')
91
            ]);
92
        } catch (\Throwable $e) {
93
            return [];
94
        }
95
    }
96
97
    /**
98
     * Render an exception into an HTTP response.
99
     *
100
     * @param  \Illuminate\Http\Request  $request
101
     * @param  \Exception  $exception
102
     * @return \Illuminate\Http\Response
103
     */
104
    public function render($request, \Exception $exception)
105
    {
106
        // Redirect upper case URLs to lower case route.
107
        $url = $request->url();
108
        $loweredCaseUrl = strtolower($url);
109
        if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException && $url !== $loweredCaseUrl) {
110
            return redirect($loweredCaseUrl);
0 ignored issues
show
Bug introduced by
The function redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

110
            return /** @scrutinizer ignore-call */ redirect($loweredCaseUrl);
Loading history...
111
        }
112
113
        // Laravel will render out the error page by default even for JSON
114
        // requests... this will return a standardized JSON response with a 403
115
        // if unauthorized.
116
        if ($exception instanceof AuthorizationException && $request->wantsJson()) {
117
            return response()->json(['message' => $exception->getMessage()], 403);
0 ignored issues
show
Bug introduced by
The function response was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

117
            return /** @scrutinizer ignore-call */ response()->json(['message' => $exception->getMessage()], 403);
Loading history...
118
        }
119
        if ($exception instanceof AdminException) {
120
            return $exception->render($request);
121
        }
122
        if ($exception instanceof TwoFactorRequiredException) {
123
            return $exception->render($request);
124
        }
125
        if ($exception instanceof TokenMismatchException) {
126
            $newMessage = $exception->getMessage() . ' ' . Lang::get('errors.refresh_page');
127
            $modifiedException = new TokenMismatchException($newMessage, $exception->getCode(), $exception);
128
            return parent::render($request, $modifiedException);
129
        }
130
        return parent::render($request, $exception);
131
    }
132
133
    /**
134
     * Convert an authentication exception into an unauthenticated response.
135
     *
136
     * @param  \Illuminate\Http\Request  $request
137
     * @param  \Illuminate\Auth\AuthenticationException  $exception
138
     * @return \Illuminate\Http\Response
139
     */
140
    protected function unauthenticated($request, AuthenticationException $exception)
141
    {
142
        if ($request->expectsJson()) {
143
            return response()->json(['error' => 'Unauthenticated.'], 401);
0 ignored issues
show
Bug introduced by
The function response was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

143
            return /** @scrutinizer ignore-call */ response()->json(['error' => 'Unauthenticated.'], 401);
Loading history...
144
        }
145
        $loginRoute = ($exception->redirectTo() !== null && $exception->redirectTo() !== '')
146
            ? $exception->redirectTo()
147
            : route('login');
0 ignored issues
show
Bug introduced by
The function route was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

147
            : /** @scrutinizer ignore-call */ route('login');
Loading history...
148
        return redirect()->guest($loginRoute);
0 ignored issues
show
Bug introduced by
The function redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

148
        return /** @scrutinizer ignore-call */ redirect()->guest($loginRoute);
Loading history...
149
    }
150
151
    /**
152
     * OVERRIDE
153
     * Render the given HttpException.
154
     *
155
     * @param  \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface  $e
156
     * @return \Symfony\Component\HttpFoundation\Response
157
     */
158
    protected function renderHttpException(HttpExceptionInterface $e)
159
    {
160
        if (!view()->exists("errors.{$e->getStatusCode()}")) {
0 ignored issues
show
Bug introduced by
The function view was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

160
        if (!/** @scrutinizer ignore-call */ view()->exists("errors.{$e->getStatusCode()}")) {
Loading history...
161
            return response()->view('errors.default', [
0 ignored issues
show
Bug introduced by
The function response was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

161
            return /** @scrutinizer ignore-call */ response()->view('errors.default', [
Loading history...
162
                'exception' => $e,
163
                'goc' => Lang::get('common/goc'),
164
                'alert' => Lang::get('common/alert'),
165
                'error' => [
166
                    'title' => 'Error'
167
                ]
168
            ], $e->getStatusCode(), $e->getHeaders());
169
        }
170
        return parent::renderHttpException($e);
171
    }
172
}
173